【问题标题】:Find result from joining a table in rails :conditions part通过在 rails 中加入表格查找结果:条件部分
【发布时间】:2013-07-23 10:11:37
【问题描述】:

目前附件是根据attachment_file_nametagsemployee_id搜索的,我也想根据员工姓名搜索,怎么办? 必须使用两个模型。

  1. 员工 - 包含员工姓名
  2. LessonplanAttachment - 包含员工的 ID。

代码部分。

def search_ajax
   @attachments = LessonplanAttachment.find(:all,
    :conditions => ["attachment_file_name LIKE ? OR tags LIKE ? OR employee_id = ?",
      "#{params[:query]}%","#{params[:query]}%",params[:query]])
end

【问题讨论】:

  • 如果您的班级获得未定义的方法joins,您能否确认您使用的是什么版本的rails?
  • rails 2,使用 rvm 1.8.7

标签: ruby-on-rails search join ruby-on-rails-2


【解决方案1】:

试试这个

LessonplanAttachment.joins("JOIN employee on employee_id").find(:all, :conditions =>
  ["attachment_file_name LIKE ? OR tags LIKE ? OR employee_id = ? OR employee.name = ?",
  "#{params[:query]}%","#{params[:query]}%",params[:query], params[:query]]

【讨论】:

  • 未定义方法`joins'
  • LessonplanAttachment 是 ActiveRecord::Base 的子类吗?
【解决方案2】:

我猜你的 LessonplanAttachment 模型中有以下关联。

belongs_to :employee

现在您可以按照以下方式更改您的代码

@attachments = LessonplanAttachment.joins([:employee]).where("attachment_file_name LIKE ? OR tags LIKE ? OR employee_id = ? OR employees.name LIKE ?", "#{params[:query]}%","#{params[:query]}%",params[:query],"#{params[:query]}%")

【讨论】:

  • 未定义的方法`joins'
【解决方案3】:

假设您在 LessonplanAttachment 类上有关联 belongs_to :employee,对于 rails 2,您可以将 :joins 属性添加到 find 上的选项。像这样的东西应该可以工作:

@attachments = LessonplanAttachment.find(:all,
 :joins => :employee,
 :conditions => [
   "attachment_file_name LIKE ? OR tags LIKE ? OR 
    employee_id = ? OR employees.name LIKE ?",
   "#{params[:query]}%","#{params[:query]}%",params[:query],"#{params[:query]}%"])

【讨论】:

    猜你喜欢
    • 2012-07-08
    • 2012-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多