Reputation: 249
If I have three classes in 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
and if I call
@item.parts
it works fine, but if I make following call
@item_part.elements
throws an error
NoMethodError: undefined method "elements"
Have I done my associations wrong or is there a different issue?
Upvotes: 0
Views: 485
Reputation: 23317
I believe you need to specify class names for these associations. If you didn't have namespacing, these would work fine out of the box. But since you have Item::Part::Element
instead of simply Element
, you have to give ActiveRecord more to go on. Try this:
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
The reason the class_names start with "::" is that it tells ActiveRecord you're namespacing from the top (root) of the namespace structure, instead of relative to the current model.
Honestly, I have a little trouble believing that @item.parts
works properly!
Upvotes: 1