Ruby On Rails, Design, Simplicity, Web 2.0, Ajax, Mac and Tons of Pizza.

Apr 08

How to retrieve find options from named scopes

Posted by Sandro Paganotti in no comments digg this add to delicious

Hi, It’s been a while since my last post, I apologize but I have been really busy with coding and testing (Cucumber is awesome!) for a quite important project. Within these days I came across this interesting trick that lets me discover how to return a ready-for-find options hash from a named_scope and also from an association.

So, let’s take this (simple) named scope for example:

named_scope :name, lambda do |query|
    firstname, lastname = query.split(" ")
    {:conditions=>{:firstname =>firstname, :lastname => lastname}}
end

By calling the method ‘proxy_options’ after the scope you’ll be able to retrieve the generated options Hash:


User.name(“Sandro Paganotti”).proxy_options 
#  {:conditions=>{:firstname=>”Sandro”, :lastname=>”Paganotti”}}
If you need to obtain the same result from an association you can use the method ‘construct_scope’ as follows

User.first.comments.send(:construct_scope)[:find]
# {:limit=>nil, :readonly=>false, :order=>nil, :include=>nil, :conditions=>”`comments`.user_id = 1”}

Sandro

Post a comment

Categories:

Tags:

Powered by Mephisto, Valid XHTML 1.1, Valid CSS - Supported by Wave Factory