0

In my Rails 3.2 app I have a has_and_belongs_to_many :notes association on Profile. Note has a type on it - "urgent" or "standard". (Note has_and_belongs_to_many :profiles.)

I'd like to be able to do something like profile.urgent_notes without building it in a method like:

def urgent_notes
  urgent_notes = Array.new
  goals.each do |g|
    if g.type == "urgent"
      urgent_notes << g
    end
  end

  urgent_notes
end

So is there a clean way to do this by adding another association? Or would something like a scope be best?

tvalent2
  • 4,959
  • 10
  • 45
  • 87

2 Answers2

1

A scope on Note would best best. scope :urgent, where(type: 'urgent')

Then you can do profile.notes.urgent to get the urgent notes.

Alex Peachey
  • 4,606
  • 22
  • 18
1

If you don't want to use a scope, here's a rewrite of your Profile method:

def urgent_notes
  self.goals.map {|g| g.type == 'urgent'}
end

You don't need to create a new array or anything. Rails and Ruby do all that work for you.

lurker
  • 56,987
  • 9
  • 69
  • 103