Created
January 28, 2011 13:39
-
-
Save metalelf0/800262 to your computer and use it in GitHub Desktop.
How to define a named scope in a habtm relation
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
# First model: tag.rb | |
# note that pomodori is a custom plural for pomodoro | |
class Tag < ActiveRecord::Base | |
has_and_belongs_to_many :pomodori | |
end | |
# Second model: pomodoro.rb | |
# here is how to define a Rails 3 scope through the join table: | |
class Pomodoro < ActiveRecord::Base | |
has_and_belongs_to_many :tags | |
scope :by_tag, lambda { |tag_text| | |
joins("join pomodori_tags, tags"). | |
where('pomodori.id = pomodori_tags.pomodoro_id | |
AND pomodori_tags.tag_id = tags.id | |
AND tags.text = ?', tag_text) | |
} | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment