Skip to content

Instantly share code, notes, and snippets.

@markmcdonald51
Created January 9, 2016 12:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markmcdonald51/19a891b8d38f67189cd5 to your computer and use it in GitHub Desktop.
Save markmcdonald51/19a891b8d38f67189cd5 to your computer and use it in GitHub Desktop.
Why not to use has_many association extension over has_many with conditions
Why not to use has_many association extension over has_many with conditions!
Has many is useful for adding in new functionality to the has_many association, however the problem with these entensions is
that Rails doesn't cache them. So every time you call object.members.requested it makes a call to the database.
has_many :organization_users
has_many :members, through: :organization_users, source: :user
has_many :members, through: :organization_users, source: :user do
def requested
where('organization_users.aasm_state = "requested"')
end
def active
where('organization_users.aasm_state = "active"')
end
def disabled
where('organization_users.aasm_state = "disabled"')
end
end
The same thing can be acheived by just making has_many with conditions like such:
has_many :organization_users
has_many :members, through: :organization_users, source: :user
has_many :active_members, through: :organization_users, source: :user,
-> { where(organization_users: {aasm_state: "requested" })}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment