ben
ben

Reputation: 29777

How do I perform this search in RoR?

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

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

Upvotes: 0

Views: 94

Answers (1)

hurikhan77
hurikhan77

Reputation: 5931

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'

Upvotes: 2

Related Questions