How do I perform this search in RoR?
This is the struc开发者_StackOverflow社区ture 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
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'
精彩评论