1

If I have table A with some fields i.e :

id
name
release_date

And I have table B which contains two table A entities i.e

id
from
to

(from and to are ids from table A)

How do I connect these two entities in model so I can use dot operator to access Bs from A?

About Design

From table A record another record A is created so I want to keep track of which was created from which record.

So this is why table B exists, so I know from which A was made from which A

4
  • Can you elaborate some more on this design? That's the relationship between A and B? Commented Jul 16, 2013 at 9:10
  • @Michael Szyndel I hope that answers ur question Commented Jul 16, 2013 at 9:22
  • So you basically have a tree of records? Why not have an additional column in A like parent_id? Commented Jul 16, 2013 at 9:29
  • And for managing tree structure I tink most popular solution is Ancestry gem github.com/stefankroes/ancestry Commented Jul 16, 2013 at 9:31

3 Answers 3

2

You can use a has_and_belongs_to_many relationship. There's more information about it in rails guide where you can check the migrations needed too.

Sign up to request clarification or add additional context in comments.

1 Comment

HABTM is generally discouraged in favour of has_many :through and it is even more discouraged to give that answer to such a broad question.
1

Try

in class B

has_many :froms, :foreign_key => "from" , :class_name=>"A"
has_many :tos, :foreign_key => "to" , :class_name=>"A" 

4 Comments

It could be has_one as well :)
This doesn't allow you to access Bs from A, you need a belongs_to in class A, but you would need a separate field based on whether it was a 'from' A or a 'to' A
When I try to access A.froms I get #<ActiveRecord::Associations::CollectionProxy:0x582f406>
A collection proxy is just a fancy array that contains instances of ActiveRecord models. try Yevgeniy's suggestion, change the has_many to has_one (maybe change to 'from' and 'to' instead of the plural to keep things sane)
0

Try to use many to many relationship using through follow this link it will clear your all doubts regarding relationships

http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.