Pluck公司相关模型的Rails中查询属性 [英] Pluck associated model's attribute in Rails query

查看:284
本文介绍了Pluck公司相关模型的Rails中查询属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Rails应用程序,收藏有很多的项目,和项目有很多的步骤

In my rails app, collections have many projects, and projects have many steps.

我想抓住的一个集合的项目步骤,所有的ID,我想知道如果我能做到这一切在一个查询。

I'd like to grab all the ids of steps in a collection's projects, and I'm wondering if I can do it all in one query.

例如,我知道我可以做以下

For example, I know I can do the following

step_ids = []
@collection.projects.each do |project|
    project.steps.each do |step|
       step_ids << step.id
    end
end

但它是可以做到类似如下:

But is it possible to do something like the following:

@ collection.projects.include(:步).pluck(step.id) //这里的语法不正确

@collection.projects.include(:steps).pluck("step.id") // syntax here is not correct

推荐答案

试试这个:

Step.joins(:project).where(projects: { collection_id: @collection.id }).pluck(:'steps.id')

请注意使用项目的连接,然后项目的where子句。第一对应belongs_to的关系,后者是db表的名称。

Note the use of project for the joins, and then projects for the where clause. The first corresponds to the belongs_to relationship, and the latter is the name of the db table.

编辑:在项目和收藏,并假设一个项目belongs_to的一个project_collection(然后的has_many之间的许多一对多的关系的情况:通过收藏,:project_collection

edit: in the case of a many-to-many relationship between projects and collections, and assuming a project belongs_to a project_collection (and then has_many :collections, through :project_collection)

Step.joins(:project => :project_collection)
    .where(project_collections: { collection_id: @collection.id })
    .pluck(:'steps.id')

这篇关于Pluck公司相关模型的Rails中查询属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆