Post

Rails 3 scopes with HABTM (has and belongs to many) relations

There are already many posts about this, but maybe this simple example will help you understand this subject even better.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 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
This post is licensed under CC BY 4.0 by the author.