ruby Rails 5 ActiveRecord查询

ki1q1bka  于 2023-11-18  发布在  Ruby
关注(0)|答案(4)|浏览(149)

型号UserArticle
在文章模型关系中定义belongs_to :user。在用户模型关系中定义has_many :articles
当我触发下面的查询时,给出成功的结果

Article.select(:name, :id).where(user_id:"fb157fc-a9353453cb95", name:"first")

字符串
但是当我触发下面的查询时,它给出一个错误

Article.select(:name, :id).where("user_id (?)","1bf4c2fc-35c37e15d4b5")

错误ActiveRecord::StatementInvalid HINT: No function matches the given name and argument types. You might need to add explicit type casts.

但是当我触发下面的查询时,它也会给出一个错误

Article.select(:name, :id).where("articles.user_id (?)","1bf4c2fc-35c37e15d4b5")

错误ActiveRecord::StatementInvalid

kcwpcxri

kcwpcxri1#

我想你可能在寻找IN查询,所以它的语法是:

user_ids = [1bf4c2fc-35c37e15d4b5,2nd_user_id, 3rd_user_id]
Article.select(:name, :id).where("user_id IN (?)",user_ids)

字符串
它将使sql查询像这样,

SELECT "articles"."name","articles"."id"  FROM "articles" WHERE (user_id IN (1bf4c2fc-35c37e15d4b5,2nd_user_id, 3rd_user_id))


如果你正在寻找一个user_id在哪里块查询,那么它的语法将是:-

user_id = 1bf4c2fc-35c37e15d4b5
Article.select(:name, :id).where("user_id = ?",user_id)


它将使SQL查询像这样:

SELECT "articles"."name","articles"."id"  FROM "articles" WHERE (user_id =
 "1bf4c2fc-35c37e15d4b5")


希望上面的两个查询能让你清楚地区分搜索多个user_id和一个user_id的IN。

liwlm1x9

liwlm1x92#

我相信这就是你要找的

Article.select(:name, :id).where("user_id =?","1bf4c2fc-35c37e15d4b5")

字符串
活动记录将第一个参数作为条件字符串,任何其他参数将替换其中的问号(?)。

vxbzzdmp

vxbzzdmp3#

您缺少=。请尝试:

Article.select(:name, :id).where("user_id = (?)","1bf4c2fc-35c37e15d4b5")

字符串
我以为你会做些更像是:

User.find_by(id: "1bf4c2fc-35c37e15d4b5").articles.select(:name, :id)


如果你不需要结果是一个包含Article示例集合的ActiveRecord::Relation,你可以这样做:

User.find_by(id: "1bf4c2fc-35c37e15d4b5").articles.pluck(:name, :id)


这将给予您一个arraysarray。我相信这会快一点,因为您没有示例化ActiveRecord对象。但是,这完全取决于您的需要。

vnzz0bqm

vnzz0bqm4#

尝试以下测试

@user_id = "fb157fc-a9353453cb95"
@articles = Article.select(:name, :id).where('user_id IN (?)', @user_id)

字符串
希望帮助

相关问题