2012-07-17 41 views
1

我有以下型號及運行的軌道3.01:Rails的套裝在加連接表

# file: app/models/product.rb 
class Product < ActiveRecord::Base 
    has_many :categories, :through => :product_categories 
    has_many :product_categories, :dependent => :destroy 
    accept_nested_attributes_for :product_categories 
end 

# file: app/models/category.rb 
class Category < ActiveRecord::Base 
    has_many :products, :through => :product_categories 
    has_many :product_categories, :dependent => :destroy 
end 

# file: app/models/product_category.rb 
class ProductCategory < ActiveRecord::Base 
    belongs_to :product 
    belongs_to :category 
end 

產品分類是我的連接表。我在產品表格中打什麼電話?我建立在Categories表或ProdcutCategories表上嗎?我只是很困惑,我應該如何嵌入我的產品。謝謝!

回答

1

該模型已被配置爲接受products_categories關聯的屬性。在你的表單只是像這樣引用它:

<%= f.fields_for :products_categories do |pc| %> 
    # fields go here 

請記住,你將需要建立新的對象爲products_categories關聯之前這種形式會呈現什麼:

products.products_categories.build 
+0

我添加到我的產品形式:< %= f.fields_for:product_categories do | pc | %> \t <%= pc.label:primary_category_name%> \t <%= pc.text_field:primary_category_name,:大小=> 65%> \t <%= pc.label:primary_category_id%> \t <%= PC .text_field:primary_category_id%> \t <%end%>並在我的產品控制器中:def new @product = Product.new @ product.product_categories.build end。我收到「未定義的方法'primary_category_name'」 – Yogzzz 2012-07-17 18:38:23

+0

您的'ProductCategory'對象不響應'primary_category_name'。這完全是另一個問題。 – 2012-07-17 22:01:25