|
Posted by Vamsi Krishna on November 20th, 2009
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. Let’s see how I used in the application
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 <%= get_select_box(Publication.scoped) %> 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
def get_select_box(items)
active_items = items.active
inactive_items = items.inactive
deleted_items = items.deleted
options = "<select>"
options += "<optgroup label='Active'>"
active_items.each do |item|
options += "<option value='#{item.id}'>#{item.name}</option>"
end
options += "<optgroup label='In-Active'>"
inactive_items.each do |item|
options += "<option value='#{item.id}'>#{item.name}</option>"
end
options += "<optgroup label='Deleted'>"
deleted_items.each do |item|
options += "<option value='#{item.id}'>#{item.name}</option>"
end
options += "</select>"
end
active,inactive and deleted named scopes are defined inside the publication model. This is the publication model 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 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. Tags: ActiveRecord, Rails, Ruby on Rails, scoped_byUnique Views: 486 Total views: 643 Follow responses at RSS 2.0. Leave a response | Trackback. Leave a Reply |