【问题标题】:Rails problems with Join search加入搜索的 Rails 问题
【发布时间】:2010-10-18 20:18:56
【问题描述】:

我正在 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")

【问题讨论】:

标签: sql ruby-on-rails join


【解决方案1】:
Profile.find_all_by_firstname(params[:keyword],
:select => "firstname, lastname, user_id",
:joins => "left outer join contacts on profiles.id = contacts.profile_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})")

但我不太确定语法

【讨论】:

  • 这可行,但我不能在 WHERE 语句中包含 params(:keyword) 而不会出错:@profiles = Profile.find_by_sql("SELECT * FROM contacts INNER JOIN profiles ON contacts.friend_id = profiles. id WHERE profiles.firstname = 关键字")
  • 如果这是您的确切代码,那么您应该将其更改为 @profiles = Profile.find_by_sql("SELECT * FROM contacts INNER JOIN profiles ON contacts.friend_id = profiles.id WHERE profiles.firstname = #{参数[:keyword]}")
猜你喜欢
  • 1970-01-01
  • 2011-12-17
  • 1970-01-01
  • 2010-12-18
  • 1970-01-01
  • 1970-01-01
  • 2020-12-01
  • 1970-01-01
  • 2016-12-21
相关资源
最近更新 更多