开发者

Rails3 scope with has_many association

I have two models, which are associated with has_many.

class User < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  be开发者_开发知识库longs_to :user
end

And migration file for creating comments table is like this:

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
  ...

To list users who posted important comment as their latest one, I tried:

scope :have_important, (joins(:comments) & Comment.order('created_at desc')).where('important = ?', true)

on user.rb. But this includes users who have posted important comment as NOT latest. How can I define that scope?

Unit test is here:

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


The name "have_important" doesn't really imply latest. Maybe what you want is two different scopes, one for important and one for recent. Then chain them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜