문제

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