views:

31

answers:

2

Is there a better way to write this

I have A Condition which previous Look Very clean and easy to understand like

Account.first.websites.last.users.find(:all,
             :conditions => {:country => "XYZ",:status => "Single",:admin => nil)

Now the big problem is that user with admin = false is not picked up.

i.e I want all the users from a specific country, having status as "Single" and admin is either "nil" (Null in database) or "false".

I manage to get desired code but doesn't seem to be happy with clarity of it.

Account.first.websites.last.users.find(:all,
    :conditions => ["country = ? AND status = ? AND admin IS NULL OR 
       admin = ?","XYZ","Single","false"])

Any help would be appreciated.

thanks

+1  A: 

Try the following:

Account.first.websites.last.users.all(:conditions => ["country = ? AND status = ? AND admin != true","XYZ","Single"])
Mr. Matt
You may need to use `admin != ?` and add a `true` parameter.
Shadwell
A: 

I would add some scopes to model:

scope :not_admin, where("admin is null or admin = ?", false)
scope :single, where("status = ?", "single")
scope :from_country, lambda {|country| where("country = ?", country}

then use it in controllers:

Account.first.websites.last.users.from_country("XYZ").single.not_admin

You can also use autogenerated scopes:

Account.first.websites.last.users.scoped_by_country("XYZ").scoped_by_status("single").not_admin

Here I left only not_admin scope.

klew