Filtering child objects in a has_many :through relationship in Rails 3

前端 未结 5 787
一个人的身影
一个人的身影 2021-02-01 19:23

Greetings,

I have an application where Companies and Users need to belong to each other through a CompanyMembership model, which c

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-01 20:29

    I made the activerecord_where_assoc gem to do this.

    With it, no need for joins or includes. Doing eager loading remains your choice, not an obligation.

    users.where_assoc_exists(:company_memberships, admin: true, company_id: @company.id)
    

    The question is unclear on how to filter the company, so I added it myself. Without this, if a user can be in multiple company, it being admin in one company could mean being treated as an admin in another company.

    The gem doesn't work in Rails 3, but we are 9 years later and Rails 4.1 and more are supported.

    Here are the introduction and examples. Read more details in the documentation.

提交回复
热议问题