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

前端 未结 5 790
一个人的身影
一个人的身影 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:25

    I believe I was going about this the wrong way, specifying conditions on company_memberships instead of users, which was what I actually wanted (a list of Users, not a list of CompanyMemberships). The solution I think I was looking for is:

    users.where(:company_memberships => {:admin => true})
    

    which generates the following SQL (for company with ID of 1):

    SELECT "users".* FROM "users"
      INNER JOIN "company_memberships"
        ON "users".id = "company_memberships".user_id
      WHERE (("company_memberships".company_id = 1))
        AND ("company_memberships"."admin" = 't')
    

    I'm not sure yet if I'll need it, but the includes() method will perform eager loading to keep down the number of SQL queries if necessary:

    Active Record lets you specify in advance all the associations that are going to be loaded. This is possible by specifying the includes method of the Model.find call. With includes, Active Record ensures that all of the specified associations are loaded using the minimum possible number of queries.queries. RoR Guides: ActiveRecord Querying

    (I'm still open to any suggestions from anyone who thinks this isn't the best/most effective/right way to go about this.)

提交回复
热议问题