Skip to content

Instantly share code, notes, and snippets.

@ariejan
Created December 7, 2012 13:05
Show Gist options
  • Save ariejan/4233163 to your computer and use it in GitHub Desktop.
Save ariejan/4233163 to your computer and use it in GitHub Desktop.
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?
@avdgaag
Copy link

avdgaag commented Dec 7, 2012

Membership.find_by_magazine_id_and_reader_id(1, 2) wrapped in a nice class method?

@avdgaag
Copy link

avdgaag commented Dec 7, 2012

class Magazine
  has_many :memberships do
    def of_reader(reader)
      find_by_reader_id(reader.id)
    end
  end
end

@yvasilkov
Copy link

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