Rails3 范围与 has_many 关联
我有两个模型,它们与 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
名称“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.