Satchel
Satchel

Reputation: 16724

How do I search through associations using Squeel in Rails 3?

I am trying to search through the model contacts associated by user_id but list the companies.

@companies_user = Company.joins{contacts}.where{:contact => {user_id => current_user}}.uniq

What I want is to search for the names of companies where there is a contact that has a user_id the same as current_user.

I haven't found an example...I used to use searchlogic, but am now in Rails 3....thanks!

Upvotes: 0

Views: 652

Answers (2)

kakubei
kakubei

Reputation: 5400

A year late, but hopefully it will help someone else.

Basically with Squeel you would do something like this:

@companies_user = Company.joins{contacts}.where{contacts.user_id == current_user}

You can take it even further and search for both something inside the joined table and the table you are querying:

@companies_user = Company.joins{contacts}.where{(contacts.user_id == current_user) & (company_name =~ 'Apple')}
# would translate to 
SELECT ... FROM...
<join statements>...
WHERE contacts.user_id = <current_user> AND company.company_name LIKE 'Apple'

See this article

It does exactly that and more.

Upvotes: 1

Bohdan
Bohdan

Reputation: 8408

It can be done vice versa

@user = User.find( current_user_id )
@company_names = @user.contacts.map{ |contact| cntact.company.name }.uniq

Upvotes: 0

Related Questions