views:

45

answers:

3

This is the structure of my database in Ruby on Rails:

user have many notes
notes have many categories
categories have many notes

I have setup this relationship with has_many :through. I use

current_user.notes

to get the notes belonging to the user. But what is the best way to get the notes belonging to the current user that have a certain category? Am I supposed to use find methods like I would on a model? Thanks for reading.

A: 

I believe it should be:

current_user.notes.all(:joins => :categories, :conditions => ["categories.name = ?", search_parameter])

Just a note that this will perform a query with an INNER JOIN to use a LEFT JOIN, you should use :include:

current_user.notes.all(:include => :categories, :conditions => ["categories.name = ?", search_parameter])
Geoff Lanotte
A: 
class User < ActiveRecord::Base 
   has_many :notes  
   has_many :categories, :through => :notes 
end 

class Note < ActiveRecord::Base
  belongs_to :user
  belongs_to :category
end 

class Category < ActiveRecord::Base 
    has_many :notes  
end 

@current_user.notes.all

I think ,You should break your many to many relationship between notes and categories.

A: 

you could add a named_scope to notes

  named_scope :with_categories, 
              lambda{|cat|
                { 
                  :joins => [:categories],
                  :conditions => ["categories.id IN (?)", cat]
                }
              }

and then you can simply use

current_user.notes.with_categories(1, 2)
Angelus