2016-03-06 83 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

任何想法,请帮助.... –