How to configure model activerecord in rails for items with multiple links
-
22-10-2019 - |
Question
I have two models, Item and Link. Each link is going to join two items together, only two. What is the best way to set up the model relationship?
I currently have this:
class Item < ActiveRecord::Base
has_many :links
end
class Link < ActiveRecord::Base
belongs_to :item1, :class_name => "Item", :foreign_key => "item1_name"
belongs_to :item2, :class_name => "Item", :foreign_key => "item2_name"
end
Is this correct? Will I run into any problems later on when I wanted to list the links for each item?
Please recommend me better alternatives, Thanks.
Solution
take a look at has one through
Something like
Item
:has_one :item, through: :links
That should link two items together through the links model
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow