Ruby on rails 拥有多个rails关联=>;命名者

Ruby on rails 拥有多个rails关联=>;命名者,ruby-on-rails,ruby,ruby-on-rails-4,Ruby On Rails,Ruby,Ruby On Rails 4,如果我在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 :it

如果我在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_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-Item::Part::Element“item\u part\u id”
self.table\u name='item\u part\u elements'
结束
类项::部分'::Item::Part::Element'
属于:项,:外键=>'item\u id'
self.table\u name='item\u parts'
结束
类项'::项::部件'
self.table_name='item'
结束
类_名称以“:”开头的原因是,它告诉ActiveRecord您是从名称空间结构的顶部(根)开始命名的,而不是相对于当前模型


老实说,我很难相信
@item.parts
能正常工作

不知道所有细节很难说。如何实例化这些实例变量?还有
NoMethodError
,但为了什么?对于
nil
?命名方法错误:在使用
Item\u part\u id
Item\u id
时隐含的Item::PartIs
self
的未定义方法“元素”和
Item\u id
?self.table\u name是的,它包括
属于:Item,:foreign\u key=>Item\u id
-应该是
:Item\u id
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