Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make an ActiveRecord scope that doesn't affect the query in Rails 3 using Arel (presumably)?

Essentially I am looking for a no-op type of relation to apply to a chain of scopes.

Lets say I have a chain of scopes:

Post.approved.published.all

Now, for debugging purposes, I wish to make the published scope do nothing at all, so that the chain will only return approved posts, regardless of whether they are published or not.

What would I return in the following method:

def self.published
  # what to return?
end
like image 591
jakeonrails Avatar asked Sep 07 '11 19:09

jakeonrails


People also ask

What is an ActiveRecord scope?

Scopes are used to assign complex ActiveRecord queries into customized methods using Ruby on Rails. Inside your models, you can define a scope as a new method that returns a lambda function for calling queries you're probably used to using inside your controllers.

How scope works in Rails?

Scopes are custom queries that you define inside your Rails models with the scope method. Every scope takes two arguments: A name, which you use to call this scope in your code. A lambda, which implements the query.

What is scope in ror?

In Ruby on Rails, named scopes are similar to class methods (“class. method”) as opposed to instance methods (“class#method”). Named scopes are short code defined in a model and used to query Active Record database.


1 Answers

Make published an alias for all, or use scoped to return a relation to which additional conditions can be chainged:

def self.published
  all
  #or
  scoped
end

I would use a scope, returning all...

scope :published, all

or, make it an alias for scoped:

scope :published, scoped
like image 100
meagar Avatar answered Oct 04 '22 13:10

meagar