我正在开发Rails 3中的小型用户应用程序,并且卡在搜索功能上。我有一个名为Profile的表,其中包含Firstname和Lastname。搜索此表时,我使用:
Profile.find_all_by_firstname(params[:keyword])
问题是我希望用户能够搜索包含联系人的表(仅限profile_id和friend_id),但我希望他们也可以在这里按名称搜索。这是怎么做到的?
例如:
John搜索Ann的名字,这是他的联系人。由于Contact表不存储名称,因此搜索必须在查询中包含Profile表。我怎么能这样做?
更新
此联接查询不仅会向所有人提取联系人,是否有人可以发现问题?
Profile.find_all_by_firstname(params[:keyword],
:select => "firstname, lastname, user_id",
:joins => "left outer join contacts on profiles.id = contacts.profile_id")
答案 0 :(得分:1)
Profile.find_all_by_firstname(params[:keyword],
:select => "firstname, lastname, user_id",
:joins => "left outer join contacts on profiles.id = contacts.profile_id")
此查询会抓取所有人,因为您只通过名字进行搜索如果您选择的联系人是特定用户的朋友,那么首先必须拥有他的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})")
但我不太确定语法