Reputation: 4594
I'm trying to make two one to one relationships in the same class in rails.
I added two columns to my class called link
post_id1 post_id2
So now I want to be able to get a link object, and do
link.post1
link.post2
But I'm getting confused about how to specify this
I assume it's something to do with
has_one :Post, => specify name so the references don't clash
I assume this is really easy, I'm just new to rails.
Upvotes: 0
Views: 487
Reputation: 4594
The other answered helped me, but it was also this I was specifically looking for
:foreign_key => "post_id1"
So the final line is
belongs_to :post_1, :class => "Post", :foreign_key => "post_id1"
Thanks for your help too!
Upvotes: 1
Reputation: 13014
In class Link
:
belongs_to :post_1, :class => "Post"
belongs_to :post_2, :class => "Post"
EDIT: [corrected belongs_to
]
Upvotes: 0
Reputation: 1975
You will need post1_id and post2_id in links table and:
belongs_to :post1, class_name: "Post"
belongs_to :post2, class_name: "Post"
In the Post model you can use has_one or has_many for back reference.
UPDATE: Here is a reference for this: choosing between belongs_to and has_one
Upvotes: 1