Home arrow Ruby-on-Rails arrow Page 2 - Action Pack Categories and Events

Action Pack Categories and Events

In this fourteenth part of a multi-part series on the Action Pack library, you'll learn how to add categories to the Events form and handle categories in the Events controller. This article is excerpted from chapter six of the book Beginning Rails: From Novice to Professional, written by Jeffery Allan Hardy, Cloves Carneiro Jr. and Hampton Catlin (Apress; ISBN: 1590596862).

Author Info:
By: Apress Publishing
Rating: 5 stars5 stars5 stars5 stars5 stars / 3
July 06, 2011
  1. · Action Pack Categories and Events
  2. · Handling Categories in the Events Controller

print this article

Action Pack Categories and Events - Handling Categories in the Events Controller
(Page 2 of 2 )

We need to let our controller know how to deal with categories. This is relatively easy. That said, it will likely be one of the most complex things you need to do in a typical controller, and to make it happen, weíll need to use a little Ruby-fu. Listing 6-19 shows how itís done. The new code is listed in bold.

Listing 6-19. Create Action Modified in app/controllers/events_controller.rb

def create @event = Event.new(params[:event])

unless params[:categories].blank? @event.categories << Category.find(params[:categories]) end

if @event.save flash[:notice] = 'Event was successfully created.' redirect_to :action => 'index'

if @event.sav

else render :action => 'new' end end

First, we check whether a list of category id values was submitted in the params hash:

unless params[:categories].blank?

If there are categories in the params , we take advantage of the fact that ActiveRecord::Base.find accepts an array of primary keys for record to find and returns an array of the objects it finds. We further take advantage of the append operator, << , and use it to append the categories collection to the existing (empty) collection con tained in @event.categories . The result is that we tack any selected categories on to the @event.categories collection, and Active Record takes care of the rest. We can then save our @event object as usual.

When we receive an update request, we need to handle things a little differently. We canít just append new categories onto the existing collection, because some categories may have been deleted. The easiest way to handle this is to reset all the @event ís category id values at once. When you use the has_and_belongs_to_many association, Active Record automatically adds a method called #{collection}_ids to both sides of the relationship, where #{collection} is the singular name of the collection. In the case of an Event that has_and_belongs_to_many categories, the category_ids method is added to every Event instance. When used, it replaces the existing collection with objects whose primary keys match those supplied. Listing 6-20 shows how this is handled, again with the modified code in bold.

Listing 6-20. Update Action Modified in app/controllers/events_controller.rb

def update @event = Event.find(params[:id])

@event.attributes = params[:event]

unless params[:categories].blank? @event.category_ids = params[:categories] end if @event.save

flash[:notice] = 'Event was successfully updated.' redirect_to :action => 'show', :id => @event else render :action => 'edit' end end

if @event.save

Instead of using the update_attributes method to update the Event object and save it in one fell swoop, we use attributes . The only difference between the two is that attributes doesnít automatically save the record. Since we want to avoid having to save twice (once to update the attributes via params and another time to update the cate gories), this makes sense. After the attributes have been set and the category_id values have been updated, we can save the record and respond accordingly to either success or failure.

Please check back for the next part of this series.

DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

blog comments powered by Disqus

- Ruby-on-Rails Faces Second Security Flaw in ...
- Ruby 2.0 Prepped for February 2013 Release
- Why LinkedIn Switched from Ruby on Rails
- Adding Style with Action Pack
- Handling HTML in Templates with Action Pack
- Filters, Controllers and Helpers in Action P...
- Action Pack and Controller Filters
- Action Pack Categories and Events
- Logging Out, Events and Templates with Actio...
- Action Pack Sessions and Architecture
- More on Action Pack Partial Templates
- Action Pack Partial Templates
- Displaying Error Messages with the Action Pa...
- Action Pack Request Parameters
- Creating an Action Pack Registration Form

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 

Developer Shed Affiliates


© 2003-2019 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials