0

我按照http://railscasts.com/episodes/17-habtm-checkboxes-revised?view=asciicast教程设置了一个 has_many through 关系,当我尝试从一个模型访问信息时,它可以工作,但不能从另一个模型访问。

我可以通过@product.category_idsand访问 Product 模型中的类别信息@product.categories,但反之则不然。我无法从 Category 模型访问 Product 信息。使用@category.product_idsor@category.products给我错误NoMethodError: undefined method 'product_ids' for #<Category:0x007fa70d430e98>

产品.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

类别.rb

class Category < ActiveRecord::Base
  attr_accessible  :product_ids

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

- 编辑 -

架构.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
4

1 回答 1

0

要访问每个对象的记录,您应该能够:

@category.products

@product.categories

这将为您提供相关的对象。

product_ids不是类别的属性,并且它accepts_attributes_for :products不像您的类别模型,因此删除attr_accessible :product_ids应该可以修复错误。

于 2013-09-26T21:01:24.897 回答