【问题标题】:Rails query interface where clause issue?Rails查询界面where子句问题?
【发布时间】:2013-05-16 04:52:12
【问题描述】:

我尝试如下运行 SQK 查询

@applicants = Applicant.where("applicants.first_name LIKE ? AND applicants.status = ?", "%#{people}%", ["new", "in-review"] )

我收到一个 MySQL 错误:

ActionView::Template::Error (Mysql2::Error: Operand should contain 1 column(s): SELECT `applicants`.* FROM `applicants`  WHERE (applicants.first_name LIKE '%sh%' AND applicants.status = 'new','in-review')):

【问题讨论】:

    标签: mysql ruby-on-rails ruby-on-rails-3 activerecord


    【解决方案1】:

    如果你想传递一个数组,最好写成

    @applicants = Applicant
        .where("applicants.first_name LIKE ?", "%#{people}%")
        .where(status: ["new", "in-review"])
    

    或使用squeel gem。

    @applicants = Applicant.where{ (status.in(["new", "in-review"]) & (first_name =~ "%#{people}%") }
    

    【讨论】:

    • 你能帮我解决这个问题吗?点击链接 pastebin.com/2vup4PWD
    • 您不能使用面向对象的表示法申请人.job.job_title,因为据我了解,job_title 是工作表的一列。您需要加入工作表。 guides.rubyonrails.org/…
    【解决方案2】:

    你必须使用mysql的IN子句

    @applicants = Applicant.where("applicants.first_name LIKE ? AND 
                                   applicants.status in (?)", 
                                   "%#{people}%", ["new", "in-review"] )
    

    【讨论】:

    • @applicants = Apply.includes(:jobs).where("applicants.first_name LIKE ? AND Candidates.location LIKE ? AND jobs.job_title LIKE ?", "%#{people}%", "%#{location}%", "%#{more_job}%")
    • 谢谢,它对我有用,但有一点改变。我使用了includes(:job)而不是includes(:jobs)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 2018-05-26
    • 1970-01-01
    • 1970-01-01
    • 2016-04-23
    相关资源
    最近更新 更多