2010-12-10 114 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」 並不真正意味着最新的。也許你想要的是兩個不同的範圍,一個重要,一個最近。然後鏈接它們。