Kim
Kim

Reputation: 2166

passing named_scope as argument

I am reusing a controller method and I need to change the scope as required.

I have stored the scope name in a session and would like to be able to do the following.

if params[:scope_name]
  session[:submission_scope_name] = params[:scope_name]
else
  session[:submission_scope_name] = "allSubs"
end


@search = Submission.session[:submission_scope_name].search do
          ...
end

The code above is giving me the following error message:

undefined method `session' for #<Class:0x00000002ad7df0>

Is there any way of passing a named_scope as an argument?

Upvotes: 0

Views: 238

Answers (1)

Veraticus
Veraticus

Reputation: 16074

You probably don't want to do this from a security standpoint: a malicious user could make a poorly-formed submission_scope that you'll just be sending straight to Submission.

That said, you're looking for the method send here. Try this instead:

Submission.send(session[:submission_scope_name].to_sym).search

send will try to call a method on that object named whatever symbol you passed in. You can read more about it in the Ruby core docs, but ultimately doing that would allow you to send whatever named scopes to Submission you want.

Upvotes: 1

Related Questions