The power of Dynamic Scope Methods in Rails

Vamsi Krishna

1 min read

After a long time I am writing this blog, I have to give a reason like everyone does (I am really really busy with project :(, I am not lying ).But, from now on I am planning to write at least one blog a month.
Anyway there are so many things I want to write about, but I am going to start with scoped_by in Rails.

I really liked the scoped_by approach in Rails. In .NET datasets are very cool, you can query on datasets, you can treat dataset as a table. I was searching for this kind of functionality in rails and found scoped_by and Ryan Bates made a very nice screencast on how to use them http://railscasts.com/episodes/112-anonymous-scopes
Let’s see how I used in the application
select box with status
I want to generate a select box as shown in the above image, it can be implemented using option_groups_from_collection_for_select helper, but for that you need two models and those two models has to have one to many association. In this scenario you need a publication model and status model, the relationship should be status has_many publications association.What if you have a status field (active/inactive) in your publication table instead of a status table, you can’t use this helper, Let’s see how scoped_by made my life easier.
I wrote my own helper method to generate this kind of select box
[source language=”Ruby”]
<%= get_select_box(Publication.scoped) %>
[/source]
Since I used Publication.scoped, I can filter my items further more and this gave me freedom of generating the select box the way I wanted.
get_select_box helper method in publications_helper
[source language=”Ruby”]
def get_select_box(items)
active_items = items.active
inactive_items = items.inactive
deleted_items = items.deleted
options = “
end
[/source]
active,inactive and deleted named scopes are defined inside the publication model.
This is the publication model
[source language=”Ruby”]
class Publication < ActiveRecord::Base # ----- SCOPE named_scope :active, :conditions => [“status = ?”, ACTIVE]
named_scope :inactive, :conditions => [“status = ?”,INACTIVE]
named_scope :deleted, :conditions => [“status = ?”, DELETED]
# —– End SCOPE
end
[/source]
I know there are many ways to approach this problem, I just want to show how cool scoped_by can be, But I am expecting some comments about the solution as well.
Please check this link as well.

Related posts:

Leave a Reply

Your email address will not be published. Required fields are marked *