Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails OR Query with JOIN and LIKE

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?

like image 671
Lalu Avatar asked Dec 10 '25 10:12

Lalu


1 Answers

Have a try with

users.joins(:posts).where(title_array.map{|title| "posts.title like '%#{title}%'"}.join(' or '))
like image 84
Bachan Smruty Avatar answered Dec 12 '25 03:12

Bachan Smruty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!