2010-08-09 86 views
0

这是我在Ruby中的数据库on Rails的结构:如何在RoR中执行此搜索?

  • 用户有许多注意事项
  • 笔记有很多种类
  • 种类有很多注意事项

笔记和类别之间的关系是has_many :through,我有一个名为NoteCategory的模型和一个note_categories表。

笔记模型有一个日期字段,它代表创建笔记的日期。

我得到的笔记与此行用户:

current_user.notes 

我怎么能提供一个日期,并取回的类别在该日期创建的所有用户的注意事项?谢谢阅读。

编辑:忘了提及,我还需要通过它们所附注的created_at字段进行排序。

编辑2:这里是实际的协会

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

鉴于你有

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

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

然后使用这个取景器:

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

user.categories.find :all, :order => 'notes.created_at' 
+0

谢谢您的回答,我会尝试一下。一个简单的问题是,我想要排序的字段实际上是notes.created_at,即类别是根据创建日期创建的,并根据它们所附加的笔记进行排序。这是你的代码吗? – ben 2010-08-10 01:06:05

+1

修正后,我了解你错了... – hurikhan77 2010-08-10 07:20:47

+0

我得到了以下错误: 无效的源反射宏:has_many:通过has_many:类别,:通过=>:笔记。使用:source来指定源反射。 – ben 2010-08-10 09:58:09