我有一个模特
class User < ActiveRecord::Base
has_many :articles
def good_publisher?
self.articles.size > 50
end
scope :good_publishers, -> where { ...???? }
end
如何表达scope
到good_publisher?
?像
scope :good_publishers, -> where { x.good_publisher? }
答案 0 :(得分:2)
范围必须是SQL语句,这里最好的办法是使用计数器缓存进行关联。
在Article
课程中,请加上:
belongs_to :user, counter_cache: true # you should already have this belongs_to, all that needs to happen is include the counter_cache
然后,创建一个包含articles_count
字段到用户的迁移:
add_column :users, :articles_count
一旦你有了这个,范围可以写成:
scope :good_publishers, where("articles_count > 50")