【问题标题】:Rails OR Query with JOIN and LIKERails OR 使用 JOIN 和 LIKE 查询
【发布时间】:2013-08-01 09:39:16
【问题描述】:

我需要在 rails 中运行这样的查询:

select users.* from users inner join posts on users.id = posts.user_id where posts.title like '%xxx%' or posts.title like '%yyy%' or posts.title like '%zzz%'

User 和 Post 是我的模型。我做了这样的事情:

title_array = ["xxx", "yyy", "zzz"]
users = User.all
users = users.joins(:posts).where(posts: { title: title_array })

但这给了我这样的 sql 查询:

select users.* from users inner join posts on users.id = posts.user_id where posts.title IN ('%xxx%', '%yyy%', '%zzz%')

我还有一个数组中的 posts.title 的值。因此,我给出了三个 OR 值的示例,但它可能因每个请求而异。

我需要 rails 方法来解决这个问题。有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: sql ruby-on-rails arel


    【解决方案1】:

    试一试

    users.joins(:posts).where(title_array.map{|title| "posts.title like '%#{title}%'"}.join(' or '))
    

    【讨论】:

    • 工作就像一个魅力!谢谢老兄的回答。
    【解决方案2】:

    试试这个

    title_array = ["xxx", "yyy", "zzz"]
    users = User.all
    condition = "1"
    title_array.each {|t| condition = condition + " OR posts.title LIKE '%#{t}%'"}
    users = users.joins(:posts).where(condition)
    

    【讨论】:

    • 这也有效,只是将单引号添加为:'%#{t}%'。我正在使用mysql数据库。谢谢老哥的回答。
    猜你喜欢
    • 2015-02-17
    • 2021-12-02
    • 1970-01-01
    • 2015-05-26
    • 2017-11-25
    • 2016-08-12
    • 2015-09-29
    • 1970-01-01
    • 2013-11-30
    相关资源
    最近更新 更多