无法在模型项中找到关联:item_option

时间:2013-11-20 20:36:09

标签: ruby-on-rails ruby activerecord ruby-on-rails-4

class Item < ActiveRecord::Base

  has_many :options, through: :item_option

end

class ItemOption < ActiveRecord::Base

  belongs_to :item
  belongs_to :option

end
class Option < ActiveRecord::Base

    has_many :items, through: :item_option


end  

我尝试将:item_option更改为item_optionsitems_options,没有任何帮助。

为什么我一直收到这个错误?

2 个答案:

答案 0 :(得分:2)

您应该在has_many :item_optionsItem模型中加入Option

答案 1 :(得分:1)

class Item < ActiveRecord::Base
  has_many item_options
  has_many :options, through: :item_options
end

class ItemOption < ActiveRecord::Base
  belongs_to :item
  belongs_to :option
end

class Option < ActiveRecord::Base    
    has_many :item_options
    has_many :items, through: :item_options
end  

如果中间模型ItemOption仅保留两个相关模型的ID,您还可以使用:has_and_belongs_to_many关联。