Home arrow Ruby-on-Rails arrow Page 4 - Callbacks and the Active Record
RUBY-ON-RAILS

Callbacks and the Active Record


In this conclusion to a five-part series that delves into the Rails framework's Active Record, you'll finish learning about validations, and take a look at callbacks. This article is excerpted from chapter five of the book Beginning Rails: From Novice to Professional, written by Jeffrey Allan Hardy, Cloves Carneiro Jr. and Hampton Catlin (Apress; ISBN: 1590596862).

Author Info:
By: Apress Publishing
Rating: 5 stars5 stars5 stars5 stars5 stars / 1
February 25, 2010
TABLE OF CONTENTS:
  1. · Callbacks and the Active Record
  2. · Validating the Format of an Attribute
  3. · Making Callbacks
  4. · Reviewing the Updated Models
  5. · Updating the User Model

print this article
SEARCH DEVARTICLES

TOOLS YOU CAN USE

advertisement
Callbacks and the Active Record - Reviewing the Updated Models
(Page 4 of 5 )

We’ve made a lot of changes to our models, so let’s make sure we’re on the same page before we move on. First, take a look at the Event model in Listing 5-27 and make sure that yours matches.

Listing 5-27. Current Event Model, in /app/models/event.rb

class Event < ActiveRecord::Base
  belongs_to :user
  has_many :registrations
  has_many :attendees, :through => :registrations, :source => :user 
  has_and_belongs_to_many :categories

  validates_presence_of :title, :location

  after_create :ensure_owner_attends
  validate     :has_not_occurred

  def is_in_the_past?
    occurs_on < Date.today
  end

  def long_title
    "#{title} - #{location} - #{occurs_on}"
  end

  protected
    def ensure_owner_attends
      unless attendees.include? user
        attendees << user
      end
  end

  def has_not_occurred
    errors.add("occurs_on", "is in the past") if occurs_on && is_in_the_past?
  end
end


blog comments powered by Disqus
RUBY-ON-RAILS ARTICLES

- 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
- Ruby on Rails Templates and Layouts
- Action Pack Controller Creation
- Writing an Action Pack Controller

Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 



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