2010-12-10 108 views
0

我有两个模型,它们与has_many关联。Rails3范围与has_many关联

class User < ActiveRecord::Base 
    has_many :comments 
end 

class Comment < ActiveRecord::Base 
    belongs_to :user 
end 

和迁移文件创建comments表是这样的:

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) 

用户。 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 
+0

我不完全确定你想要达到的目标。你能写一个测试/规范吗? – iain 2010-12-10 18:46:36

+0

增加了单元测试。 – JayKay 2010-12-10 19:40:15

+0

在一个不相关的话题上,你是否从Jamiroquai的前人名字中指出自己的名字?爱那个乐队:) – Samo 2010-12-13 16:04:26

回答

1

名称 “have_important” 并不真正意味着最新的。也许你想要的是两个不同的范围,一个重要,一个最近。然后链接它们。