2016-03-06 84 views
1

我有兩種型號。產品和產品價格(包括表格產品和產品價格),每種產品都有一個價格。我想爲兩個模型創建一個表單,但是在將解決方案複製到類似的場景之後,我的表單仍然沒有顯示價格字段。新形式的多種型號 - 導軌

class Product < ActiveRecord::Base 
    belongs_to :user 
    has_one :ProductPrice 

    accepts_nested_attributes_for :ProductPrice 
end 

class ProductPrice < ActiveRecord::Base 
    belongs_to :Product 
end 

class ProductsController < ApplicationController 

    def new 
     @product = Product.new 
     @product_price = @product.build_ProductPrice 
    end 

end 


<%= form_for @product, url: user_product_path do |f| %> 
    <div class="form-group"> 
     <%= f.text_field :product_name, placeholder: 'name', class: 'form- control' %> 
    </div> 

    <% f.fields_for @product_price do |b| %> 
    <%= b.text_field :price, placeholder: 'Enter price', class: 'form-control' %> 
    <%end%> 
<% end%> 

任何想法?我是否正確地參考了模型?

編輯:固定。它需要是<%= fields_for .... 等號丟失

回答

1

試試這個

class Product < ActiveRecord::Base 
    belongs_to :user 
    has_one :product_price 

    accepts_nested_attributes_for :product_price 
end 

class ProductPrice < ActiveRecord::Base 
    belongs_to :product 
end 

class ProductsController < ApplicationController 
    def new 
     @product = Product.new 
     @product.product_price.build 
    end 
end 


<%= form_for @product, url: user_product_path do |f| %> 
    <div class="form-group"> 
     <%= f.text_field :product_name, placeholder: 'name', class: 'form-control' %> 
    </div> 

    <%= f.fields_for :product_price do |b| %> 
     <%= b.text_field :price, placeholder: 'Enter price', class: 'form-control' %> 
    <%end%> 
<% end%> 
+0

仍然得到相同的錯誤「未定義的方法'建立爲零:NilClass」 –

0

首先,突出的是在Rails中使用大寫字母。是的,你寫class ProductPrice是正確的,但你應該在其他地方使用蛇案例,如:product_price

你可以嘗試以下方法:

class Product < ActiveRecord::Base 
    belongs_to :user 
    has_one :product_price 

    accepts_nested_attributes_for :product_price 
end 

class ProductPrice < ActiveRecord::Base 
    belongs_to :product 
end 

class ProductsController < ApplicationController 
    def new 
    @product = Product.new 
    @product_price = @product.product_price.build 
    end 
end 


<%= form_for @product, url: user_product_path do |f| %> 
    <div class="form-group"> 
    <%= f.text_field :product_name, placeholder: 'name', class: 'form-control' %> 
    </div> 

    <% f.fields_for @product_price do |b| %> 
    <%= b.text_field :price, placeholder: 'Enter price', class: 'form-control' %> 
    <%end%> 
<% end%> 

旁註但product.product_price.price感覺怪怪的。取決於你的結構的其餘部分,但沒有必要在這裏建立一個協會,只需將價格存儲在產品上即可。

+0

我將開始使用蛇的情況下(相當新的回報率)。我嘗試了你的建議,現在在@product_price = @ product.product_price.build上得到以下錯誤「未定義方法'構建'爲零:NilClass」。關於方面,同意,將改變產品包括價格,但我確實需要弄清楚以備將來使用。 –

+0

任何想法,請幫助.... –