范围和实例方法

时间:2014-12-31 11:37:18

标签: ruby-on-rails ruby ruby-on-rails-4

我有一个模特

class User < ActiveRecord::Base
  has_many :articles

  def good_publisher?
    self.articles.size > 50
  end

  scope :good_publishers, -> where { ...???? }
end

如何表达scopegood_publisher??像

这样的东西

scope :good_publishers, -> where { x.good_publisher? }

1 个答案:

答案 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")