Ian Armit
Ian Armit

Reputation: 673

How to get the through instance in a has_many :through relation

I have a has_many :through relation models like:

#foo
has_many :bars, through: link
has_many :links

#link
belongs_to :bar
belongs_to :foo

#bar
has_many :foos, through: link
has_many :links

In a situation where I have a instance of a foo and a instance of a bar how can I get the specific link instance that joins the two together(if it exists)?

Upvotes: 2

Views: 73

Answers (2)

Jason Swett
Jason Swett

Reputation: 45094

I think you could do

foo.links.find_by_bar_id(bar.id)

Upvotes: 3

rewritten
rewritten

Reputation: 16435

Maybe

foo.links.where(bar_id: bar.id).first

will do?

Upvotes: 3

Related Questions