Is normal or a best practice to have chained scopes in controllers actions?
18 views
Skip to first unread message
Nelson Senna
unread,
May 19, 2016, 2:55:49 AM5/19/16
Reply to author
Sign in to reply to author
Forward
Sign in to forward
Delete
You do not have permission to delete messages in this group
Copy link
Report message
Show original message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to Ruby on Rails: Talk
Hey, there!
I'm pretty new to Rails so this may be a really stupid question but, I googled it and found just one specific reference (http://craftingruby.com/posts/2015/06/24/say-no-to_chained-scopes.html). In the application I'm working on there are some controller actions chaining scopes like this:
@results = @person.male.adult.left_handed
Is it normal? There are best practices on chaining scopes like: you can chain maximum 2 scopes?
Cheers!
Greg Navis
unread,
May 19, 2016, 5:06:20 AM5/19/16
Reply to author
Sign in to reply to author
Forward
Sign in to forward
Delete
You do not have permission to delete messages in this group
Copy link
Report message
Show original message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to rubyonra...@googlegroups.com
Composing scopes is completely normal - they are clear, easy to test and can serve as building blocks. What you need to keep in mind is to keep your code DRY.
For example, if you have an e-commerce site selling guitars and from the data you see that high-end left-handed guitars are most often bough by male left-handed adults then you don't want to litter the code with multiple occurrences of `Person.male.adult.left_handed`. This is an implementation detail. You should define a scope (or a class method) `Person.best_high_end_left_handed_buyers` and define it to equal `Person.male.adult.left_handed`. If requirements change at a later point in time you can just change the definition. (Alternatively you can define a private method that returns the scope in your controller).
TL;DR: It's normal to chain scopes but keep your code DRY and make your code express your intent.
--
Greg Navis
I help tech companies to scale Heroku-hosted Rails apps.