2010-10-18 62 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