3

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.

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

close, but what I really need is the full statement, not just the where clauses. In this case, I'm dealing specifically with joins, so where_clauses doesn't really help.
0

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.

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.