2

I have a model

class User < ActiveRecord::Base
  has_many :articles

  def good_publisher?
    self.articles.size > 50
  end

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

How do I express the scope through good_publisher?? Something like

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

5
  • What did you mean by express the scope through good_publisher? method? Commented Dec 31, 2014 at 11:39
  • @Surya, I mean, use user.good_publisher? in -> where { .... } Commented Dec 31, 2014 at 11:41
  • good_publisher? is an instance method, while a scope creates class method, so no... there's no way you can use instance method in a scope. What are you trying to do? Commented Dec 31, 2014 at 11:43
  • @Surya, calculate the total number of the "good_publishers". Commented Dec 31, 2014 at 11:50
  • No, I meant what are you planning to do with this scope? i.e. what are you intending to do with User. good_publishers and user.good_publisher? ? Commented Dec 31, 2014 at 12:03

1 Answer 1

2

The scope has to be a SQL statement, your best bet here is to use a counter cache for the association.

At the Article class, include this:

belongs_to :user, counter_cache: true # you should already have this belongs_to, all that needs to happen is include the counter_cache

Then, create a migration that includes the articles_count field to user:

add_column :users, :articles_count

Once you have this, the scope can be written as:

scope :good_publishers, where("articles_count > 50")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.