【问题标题】:Rails3 scope with has_many association具有 has_many 关联的 Rails3 范围
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 2011-10-05
    • 1970-01-01
    • 2015-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多