I am in need to run a query like this in 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%'
Where User and Post are my Models. I did something like this:
title_array = ["xxx", "yyy", "zzz"]
users = User.all
users = users.joins(:posts).where(posts: { title: title_array })
but this gives me sql query like this:
select users.* from users inner join posts on users.id = posts.user_id where posts.title IN ('%xxx%', '%yyy%', '%zzz%')
Also I have the value of posts.title in an array. So I have given example with three OR values but it might vary with every request.
I need the rails way to solve this. Can somebody help me figure out this please?
尝试一下
users.joins(:posts).where(title_array.map{|title| "posts.title like '%#{title}%'"}.join(' or '))
Try this
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.