質問

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?

役に立ちましたか?

解決

Have a try with

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)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top