2010-10-18 60 views
0

我正在Rails 3中开发一个小型用户应用程序,并且停留在搜索功能上。我有一个名为Profile的表,其中包含Firstname和Lastname。当搜索这个表我使用:加入搜索导轨问题

Profile.find_all_by_firstname(params[:keyword]) 

的事情是,我希望用户能够搜索保存的联系人表(PROFILE_ID只有friend_id),但我希望他们能够按名称这里SEACH太。这是如何完成的?

例如:

约翰搜索名称安这是他的接触。由于联系人表不存储名称,因此搜索必须在查询中包含配置文件表。我怎样才能做到这一点?

UPDATE

此连接查询获取每个人不仅接触,任何人都可以发现一个问题呢?

Profile.find_all_by_firstname(params[:keyword], 
:select => "firstname, lastname, user_id", 
:joins => "left outer join contacts on profiles.id = contacts.profile_id") 
+0

嗨你能展示你的迁移? – Bohdan 2010-10-18 20:53:39

+0

嗨,当然。 http://pastebin.com/5930zaJF – 2010-10-18 21:00:16

回答

1
Profile.find_all_by_firstname(params[:keyword], 
:select => "firstname, lastname, user_id", 
:joins => "left outer join contacts on profiles.id = contacts.profile_id") 

,因为你只SERCH由姓如果whant选择属于特定用户的朋友接触,首先你必须有自己的ID,然后在你应该添加到您的条件,这个查询获取大家

current_user = Profile.first 
Profile.find(:all, 
      :conditions => ["profiles.firstname = ? AND contacts.friend_id = ?", params[:keyword], current_user.id], 
      :joins => :contacts) 

或使加盟条件

current_user = Profile.first 
Profile.find_all_by_firstname(params[:keyword], 
:select => "firstname, lastname, user_id", 
:joins => "INNER JOIN contacts on (profiles.id = contacts.profile_id AND contacts.friend_id = #{current_user.id})") 

,但我不太清楚有关语法

+0

这个工程,但我不能在WHERE语句中包含参数(:关键字)而不会收到错误: @profiles = Profile.find_by_sql(“SELECT * FROM contacts INNER JOIN profiles ON ON contacts。 friend_id = profiles.id WHERE profiles.firstname = keyword“) – 2010-10-18 21:35:58

+0

如果这是您的确切代码,那么您应该将其更改为@profiles = Profile.find_by_sql(”SELECT * FROM contacts INNER JOIN profiles ON contacts.friend_id = profiles.id WHERE profiles.firstname =#{params [:keyword]}“) – Bohdan 2010-10-19 09:18:46