Pluck associated model's attribute in Rails query

后端 未结 2 1999
忘了有多久
忘了有多久 2021-02-19 03:13

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

I\'d like to grab all the ids of steps

2条回答
  •  没有蜡笔的小新
    2021-02-19 03:28

    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. The first corresponds to the belongs_to relationship, and the latter is the name of the db table.

    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')
    

提交回复
热议问题