开发者

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 开发者_如何学Pythonof 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!


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.


It can be done vice versa

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜