Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql Rails或带有JOIN等的查询_Sql_Ruby On Rails_Arel - Fatal编程技术网

Sql Rails或带有JOIN等的查询

Sql Rails或带有JOIN等的查询,sql,ruby-on-rails,arel,Sql,Ruby On Rails,Arel,我需要在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

我需要在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 })
select users.* from users inner join posts on users.id = posts.user_id where posts.title IN ('%xxx%', '%yyy%', '%zzz%')
但这给了我如下sql查询:

title_array = ["xxx", "yyy", "zzz"]
users = User.all
users = users.joins(:posts).where(posts: { title: title_array })
select users.* from users inner join posts on users.id = posts.user_id where posts.title IN ('%xxx%', '%yyy%', '%zzz%')
我还有一个数组中posts.title的值。所以我给出了三个或三个值的示例,但它可能随每个请求而变化

我需要解决这个问题的方法。谁能帮我弄清楚这个问题吗?

试试看

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

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数据库。谢谢你的回答,伙计。