2011-10-06 50 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

它确实如此。