Created
December 7, 2012 13:05
-
-
Save ariejan/4233163 to your computer and use it in GitHub Desktop.
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
class Reader | |
has_many :memberships | |
has_many :magazines, through: :memberships | |
end | |
class Membership | |
belongs_to :reader | |
belongs_to :magazine | |
end | |
class Magazine | |
has_many :memberships | |
has_many :readers, through: :memberships | |
end | |
# What's the easiest way to get the `Membership` for | |
# a given Reader and Magazine? | |
@reader.memberships.find_by_magazine_id(@magazine.id) | |
# Or is there a better way? |
class Magazine
has_many :memberships do
def of_reader(reader)
find_by_reader_id(reader.id)
end
end
end
Nice solution. Personally I prefer association with :extend option as more structural way
class Magazine
module FinderExtension
def of_reader(reader)
find_by_reader_id(reader.id)
end
end
has_many :memberships, extend: FinderExtension
end
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Membership.find_by_magazine_id_and_reader_id(1, 2)
wrapped in a nice class method?