Reputation: 155
Groups and users have has_many through relationships on the table user_roles, which specifies what role users have in each group (pending, member, admin, etc). For a given group, how might I return all users matching a particular role in that group such that the code is DRY and eager loads the appropriate associations?
class Group < ActiveRecord::Base
has_many :user_roles, dependent: :destroy
has_many :users, through: :user_roles
def members(role)
self.users.includes(:user_roles).where("user_role.role = ?", role)
# Returns following error message:
# PG::UndefinedTable: ERROR: missing FROM-clause entry for table "user_role"
end
Upvotes: 0
Views: 57
Reputation: 1068
Your table name probably 'user_roles' and not 'user_role'. Change the name of table in your where clause to 'user_roles'.
def members(role)
self.users.includes(:user_roles).where("user_roles.role = ?", role)
end
Upvotes: 3