0

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.

Chris Barry
  • 4,564
  • 7
  • 54
  • 89

3 Answers3

1

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

Yuri Golobokov
  • 1,829
  • 12
  • 11
1

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!

Chris Barry
  • 4,564
  • 7
  • 54
  • 89
0

In class Link:

belongs_to :post_1, :class => "Post"
belongs_to :post_2, :class => "Post"

EDIT: [corrected belongs_to]

kiddorails
  • 12,961
  • 2
  • 32
  • 41