如果我在Rails中有三门课:
class Item::Part::Element < ActiveRecord::Base
belongs_to :item_part, :foreign_key => 'item_part_id'
self.table_name = 'item_part_elements'
end
class Item::Part < ActiveRecord::Base
has_many :elements
belongs_to :item, :foreign_key => 'item_id'
self.table_name = 'item_parts'
end
class Item < ActiveRecord::Base
has_many :parts
self.table_name = 'item'
end
如果我打电话
@item.parts
它工作正常,但如果我拨打以下电话
@item_part.elements
引发错误
NoMethodError: undefined method "elements"
我的关联是否做错了,还是有其他问题?
我相信您需要为这些关联指定类名。如果您没有命名空间,则可以立即使用。但是由于您没有Item::Part::Element
简单地Element
拥有,所以必须给ActiveRecord更多的东西。试试这个:
class Item::Part::Element < ActiveRecord::Base
belongs_to :item_part, :foreign_key => 'item_part_id'
self.table_name = 'item_part_elements'
end
class Item::Part < ActiveRecord::Base
has_many :elements, :class_name => '::Item::Part::Element'
belongs_to :item, :foreign_key => 'item_id'
self.table_name = 'item_parts'
end
class Item < ActiveRecord::Base
has_many :parts, :class_name => '::Item::Part'
self.table_name = 'item'
end
class_names以“ ::”开头的原因是,它告诉ActiveRecord您是从名称空间结构的顶部(根)开始命名空间,而不是相对于当前模型。
老实说,我在相信它能@item.parts
正常工作方面有些麻烦!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句