is there a better DRY code writing for this scope ?

12 views
Skip to first unread message

Erwin

unread,
Nov 21, 2012, 8:33:11 AM11/21/12
to rubyonra...@googlegroups.com
I wrote this scope in my Subdomain model :

  scope :in_account, lambda { |account_id|
    if account_id == "*"
      where("account_id >= ?", 0)
    else
      where(account_id: account_id) 
    end
  }

where account_id == '*'  then all subdomain instances are selected
when account_id is given , only subdomain instances in this account are selected

is there a better writing ?

thanks for feedback

Jim Ruther Nill

unread,
Nov 21, 2012, 9:03:51 AM11/21/12
to rubyonra...@googlegroups.com
you can use scoped instead

account_id == '*' ? scoped : where(account_id: account_id)  
 

thanks for feedback

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonra...@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-ta...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msg/rubyonrails-talk/-/3xoM8jq4ED8J.
For more options, visit https://groups.google.com/groups/opt_out.
 
 



--
-------------------------------------------------------------
visit my blog at http://jimlabs.heroku.com

Erwin

unread,
Nov 21, 2012, 9:58:55 AM11/21/12
to rubyonra...@googlegroups.com
Great !

Thanks Jim

Dave Aronson

unread,
Nov 21, 2012, 1:17:34 PM11/21/12
to rubyonra...@googlegroups.com
Try:

scope :in_account, lambda { |account_id|
where(account_id: account_id) if account_id != "*"
}

If the conditional fails, this will just not interfere with the query.

If it's possible that account_id will be nil or blank (as on a page
accessed w/o passing any params), tack "&& account_id.present?" onto
the conditional.

-Dave

--
Dave Aronson, the T. Rex of Codosaurus LLC,
secret-cleared freelance software developer
taking contracts in or near NoVa or remote.
See information at http://www.Codosaur.us/.
Reply all
Reply to author
Forward
0 new messages