简体   繁体   English

在Rails查询中获取关联模型的属性

[英]Pluck associated model's attribute in Rails query

In my rails app, collections have many projects , and projects have many steps . 在我的rails应用程序中, 集合有许多项目 ,项目有很多步骤

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. 我想抓住集合项目中的所有步骤ID,我想知道我是否可以在一个查询中完成所有操作。

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(:steps).pluck("step.id") // syntax here is not correct @collection.projects.include(:steps).pluck("step.id") //这里的语法不正确

Try this: 尝试这个:

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

Note the use of project for the joins, and then projects for the where clause. 注意project用于连接,然后用于where子句的projects The first corresponds to the belongs_to relationship, and the latter is the name of the db table. 第一个对应于belongs_to关系,后者是db表的名称。

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 ) 编辑:在项目和集合之间存在多对多关系的情况下,假设项目为belongs_to project_collection(然后是has_many :collections, through :project_collection

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

Unfortunately, I don't think that we could do it through AR in a single query. 不幸的是,我不认为我们可以通过AR在单个查询中完成它。 You could do a nested query below to retrieve it in two queries to the database: 您可以在下面执行嵌套查询,以便在对数据库的两个查询中检索它:

Step.includes(:projects)
    .where(projects: { id: Projects.includes(:collections)
    .where(collections: { id: @collections.id }).pluck(:id) } )
    .pluck(:id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM