2013-09-26 35 views
0

我跟着http://railscasts.com/episodes/17-habtm-checkboxes-revised?view=asciicast教程通过关系成立的has_many,当我尝试从一个模型获取信息它的工作原理,但不是从其他只做我的has_many之一。为什么虽然型号工作

我可以通过@product.category_ids@product.categories从产品型号访问类别信息,但反过来却不是这样。我无法从类别模型中访问产品信息。使用@category.product_ids@category.products给我的错误NoMethodError: undefined method 'product_ids' for #<Category:0x007fa70d430e98>

Product.rb

class Product < ActiveRecord::Base 
    attr_accessible :category_ids 

    has_many :categorizations 
    has_many :categories, through: :categorizations 
    accepts_nested_attributes_for :categorizations, :allow_destroy => true 
end 

Category.rb

class Category < ActiveRecord::Base 
    attr_accessible :product_ids 

    has_many :categorizations 
    has_many :products, through: :categorizations 
end 

- 编辑 -

Schema.rb

ActiveRecord::Schema.define(:version => 20130926192205) do 

    create_table "categories", :force => true do |t| 
    t.string "name" 
    t.datetime "created_at",  :null => false 
    t.datetime "updated_at",  :null => false 
    end 

    create_table "products", :force => true do |t| 
    t.string "name" 
    t.datetime "created_at",   :null => false 
    t.datetime "updated_at",   :null => false 
    end 

    create_table "categorization", :force => true do |t| 
    t.integer "product_id" 
    t.integer "category_id" 
    t.datetime "created_at",  :null => false 
    t.datetime "updated_at",  :null => false 
    end 

    add_index "categorization", ["product_id", "category_id"], :name => "index_categorization_on_product_id_and_category_id", :unique => true 
    add_index "categorization", ["product_id"], :name => "index_categorization_on_product_id" 
    add_index "categorization", ["category_id"], :name => "index_categorization_on_category_id" 

end 
+0

什么是您的架构是什么样子? – Oliver

+0

在上面添加了它。 –

回答

0

要访问记录从每一个对象,你应该能够:

@category.products 

@product.categories 

这会给你的相关对象。

product_ids不属于某个类别的属性,也没有accepts_attributes_for :products之类的类别模型,因此删除attr_accessible :product_ids应该修复该错误。

+0

我都试过加'accepts_nested_attributes_for:分类已,:allow_destroy => TRUE'到'Category'模型被刚刚卸下'accepts_attributes_for:products'。在这两种情况下,调用'@ category.products'都会导致#错误产生相同的'NoMethodError:undefined method'产品。 –

+0

好吧,它出于某种原因现在工作...不知道为什么。 –

相关问题