Rails3 范围与 has_many 关联

发布于 2024-10-07 05:22:28 字数 878 浏览 0 评论 0原文

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

class User < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :user
end

用于创建评论表的迁移文件如下:

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

I have two models, which are associated with has_many.

class User < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

信仰 2024-10-14 05:22:28

名称“have_important”并不真正意味着最新。也许您想要的是两种不同的范围,一种用于重要,一种用于最近。然后将它们链起来。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文