2011-10-06 49 views
0

我正在嘗試搜索user_id關聯的模型聯繫人,但列出了這些公司。如何在Rails 3中使用Squeel搜索關聯?

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

我想要搜索的公司的名稱有一個user_id與current_user相同的聯繫人。

我還沒有找到一個例子......我曾經使用過searchlogic,但現在在Rails 3中......謝謝!

回答

0

可以反之亦然

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

確實有幫助嗎? – Angela

1

做晚了一年,但希望它會幫助別人。

基本上與Squeel你會做這樣的事情:

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

你可以把它更進一步,搜索兩個東西連接表內,要查詢的表:

@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' 

請參見this article

它確實如此。