【发布时间】:2011-05-23 15:55:38
【问题描述】:
我有两个模型,它们与 has_many 相关联。
class User < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :user
end
创建cmets表的迁移文件是这样的:
class CreateComments < ActiveRecord::Migration
def self.up
create_table :comments do |t|
t.string :body
t.boolean :important, :default => false
t.references :user
t.timestamps
end
end
...
为了将发布重要评论的用户列为最新评论,我尝试了:
scope :have_important, (joins(:comments) & Comment.order('created_at desc')).where('important = ?', true)
在 user.rb 上。但这包括将重要评论发布为非最新的用户。如何定义该范围?
单元测试在这里:
test "Scoped user's latest comment should be important" do
User.have_important.each do |user|
assert_equal user.comments.last.important, true
end
end
【问题讨论】:
-
我不完全确定您要达到的目标。你能为它写一个测试/规范吗?
-
在一个不相关的话题上,你是用 Jamiroquai 的主唱来命名自己的吗?喜欢那个乐队:)
标签: ruby-on-rails ruby-on-rails-3 scope has-many