views:

64

answers:

1

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

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

The relationship between notes and categories is has_many :through, I have a model named NoteCategory and a note_categories table.

The note model has a date field, which represents the date the note was created.

I get the notes for the user with this line:

current_user.notes

How can I provide a date and get back the categories for all the user's notes that were created on that date? Thanks for reading.

edit: Forgot to mention that I also need the categories to be ordered by the created_at field of the note they are attached to.

edit 2: here are the actual associations

user.rb

has_many :notes

note.rb

belongs_to :user 
has_many :note_categories
has_many :categories, :through => :note_categories

category.rb

has_many :note_categories
has_many :notes, :through => :note_categories
+2  A: 

Given you have

class User
  has_many :notes
  has_many :categories, :through => :notes
end

class Note
  has_many :categories # <-- source reflection
end

then use this finder:

user.categories.all(:order => 'notes.created_at')

or

user.categories.find :all, :order => 'notes.created_at'
hurikhan77
Thanks for your answer, I'll try it out. A quick question, the field I want to sort on is actually notes.created_at, i.e. the categories are sorted based on the created at date of the note they are attached to. Is that what your code does?
ben
Revised, I understood you wrong...
hurikhan77
I got the following error:Invalid source reflection macro :has_many :through for has_many :categories, :through => :notes. Use :source to specify the source reflection.
ben
Please amend your original question with how you exactly defined your models...
hurikhan77
Usually it complains about source reflection if it cannot find the source of the association in the model referenced by :through. I guess you use a "has_and_belongs_to_many" approach - not sure if it would accept that.
hurikhan77
Hey, sorry I took so long to respond! I have added the model definitions into the original question. Thanks for your help!
ben
@ben so you are having a double indirection...
hurikhan77