Created
January 9, 2016 12:44
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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