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

前端 未结 5 788
一个人的身影
一个人的身影 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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-01 20:06

    I stumbled across this answer and believe that nowadays there is a nicer way using has_many association scopes (has_many documentation):

    has_many :admins, -> { where(admin: true) }, through: :company_memberships, class_name: :user
    

    The second parameter of a has_many association can be a proc or lambda that contains your filter.

提交回复
热议问题