Lukas
Lukas

Reputation: 3235

Rails 3 get sql from scope

Is there a way to get the sql for JUST a scope? So I want to do something like:

   class Presentation < ActiveRecord::Base
      has_many :calls
      has_many :recordings, :through => :calls

      scope :with_recordings, joins(:calls).joins(:recordings)
   end

And then be able to get the sql for that scope.

Presentations.with_recordings.sql returns the entire sql statement, including the SELECT statement. All I want is the sql added by the scope. Figure there ought to be a way to do this.

Upvotes: 3

Views: 1412

Answers (2)

Dave Smylie
Dave Smylie

Reputation: 2693

I agree with ctcherry about this not being very useful, but having said that, I needed to do this for a project I was working on. We needed to duplicate the sql in the scopes to allow us to reuse the sql across different types of searches. Rather that have to maintain the same sql in two different places, I choose to extract the sql from the scope.

The code below is what I came up with. It's ugly, but works under Rails 3.0

def extract_named_scope_clause(scope, args)
  # where_clauses will return an array of clauses for an entire relationship.
  # As this is only run a single scope, we only ever care about the first.....
  clause, *bind_vars = self.send(scope, args).where_clauses.first
  # prefix 'and ' to the string, add some spaces and append any bind variables
  if clause
    [" and #{clause} ", bind_vars]
  else
    nil
  end
end

Upvotes: 3

Chris Cherry
Chris Cherry

Reputation: 28554

This wouldn't really make sense, as there is no standard way to represent SQL "fragments".

The different kinds of SQL "fragments" that can be added and manipulated by a scope don't really have a clean way to be represented by themselves without being part of a complete SQL statement. A fragment could be "JOIN users ON users.id = orders.user_id" or it could be "WHERE active = 1". How would you return these without them being part of a complete SQL statement? This is most likely why there is no mechanism to retrieve them other than the one you have already discovered that just returns the complete SQL statement.

Upvotes: 0

Related Questions