How to use ActiveRecord Callbacks in Rails

Rails3Callbacks are a great technique for achieving simplicity and flexibility. A callback allows you to run some code (usually a method) automatically when another piece of code runs. In Rails, you’ll commonly see callbacks that run before, after or even around other bits of code. Callback functions are minimizing the length of codes in controllers.

Implementing Callbacks

There are four types of callbacks accepted by the callback macros:

  • Method references (symbol)
  • Callback objects
  • Inline methods (using a proc)
  • Inline eval methods (using a string) – deprecated

Here is the list of some useful callback functions while saving AcriveRecord objects

  • before_save
  • after_save

before_save:

This method is called before an ActiveRecord object is saved.

class Post < ActiveRecord::Base before_save :update_slug protected def update_slug self[:slug] = [year, season_slug, season_type_slug].compact.join '/' end end

after_save:
Once the active record object saved some method will be fired in that scenario we have to use the after_save callback.

class Post < ActiveRecord::Base after_save :handle_status_changed protected def handle_status_changed Setting.create(:post_id=>self.id , :status => true) end end

How To Implement Event Calendar In Rails App

Event calendar is a way to show multiple, overlapping events across calendar days and rows. This is an interface to add events, edit events, & destroy event. In Rails there is a gem/plugin “event_calendar” to implement it just like Google calendar.

The following steps demonstrate the implementation of event_calendar in both Rails 2.3.x and Rails3.x environment.

Step#1 –

Installing the gem/plugin

  • In rails 2.3.x

Install the required plugin from below path

script/plugin install git://github.com/elevation/event_calendar.git

Generate the necessary static file and example

script/generate event_calendar
  • In rails 3.x

Install the required gems

gem 'event-calendar', :require => 'event_calendar'

Run “bundle install

You can also use as a Plugin, to install plugin

rails plugin install git://github.com/elevation/event_calendar.git

Generate the necessary static file for the event calendar

rails generate event_calendar

Step#2

Include the necessary style sheet & java-script into your layout/view

<%= stylesheet_link_tag "dialog","fullcalendar","jquery-ui","style" %>
<%= javascript_include_tag "jrails1/fullcalendar.js","jrails1/jquery-
ui.js","jrails1/gcal.js","jrails1/jrails.js","jrails1/jquery.validate.js"%>

Step#3

Create a migration file to add necessary columns as follows

class CreateEvents < ActiveRecord::Migration
def self.up
create_table :events do |t|
t.string :name
t.datetime :start_at
t.datetime :end_at
t.timestamps
end
end
def self.down
drop_table :events
end
end

Step#4

Add the necessary paths to the “config/routes” file

  • In Rails 2.3.x
map.calendar '/calendar/:year/:month', :controller => 'calendar', :action => 'index',
 
:requirements => {:year => /d{4}/, :month => /d{1,2}/}, :year => nil, :month => nil
  • In Rails3.x
match '/calendar(/:year(/:month))' => 'calendar#index', :as => :calendar, :constraints => {:year => /d{4}/, :month => /d{1,2}/}

Step#5

Change the Event model to add the calendar as follows

class Event < ActiveRecord::Base
has_event_calendar
end

Step#6

Modify the Calendar controller as follows

class CalendarController < ApplicationController
def index
@month = (params[:month] || Time.zone.now.month).to_i
@year = (params[:year] || Time.zone.now.year).to_i
@shown_month = Date.civil(@year, @month)
@event_strips = Event.event_strips_for_month(@shown_month)
end
end

Step#7

You can also override the events method in helpers/calendar_helper.rb

module CalendarHelper
def month_link(month_date)
link_to(I18n.localize(month_date, :format => "%B"), {:month => month_date.month, :year => month_date.year})
end
# custom options for this calendar
def event_calendar_options
{
:year => @year,
:month => @month,
:event_strips => @event_strips,
:month_name_text => I18n.localize(@shown_month, :format => "%B %Y"),
:previous_month_text => "<< " + month_link(@shown_month.prev_month),
:next_month_text => month_link(@shown_month.next_month) + " >>"
}
end
def event_calendar
calendar event_calendar_options do |args|
event = args[:event]
%(<a href="/events/#{event.id}" title="#{h(event.name)}">#{h(event.name)}</a>)
end
end
end

Step#8

Add the following code to display the calendar in the view file

<%= event_calendar %>

See Also: Security Checks you must do before Rails App release

I hope it helps you. Planning anything in Ruby on Rails? Get in touch with Andolasoft experts. Feel free to give your valuable feedback.

How To Generate Barcode Using Barby Gem In Rails 2.3.8

A barcode is a series of vertical black lines with white spaces in between. This series of lines and spaces can be read by a device that can decode them. This would be a barcode reader.

In Ruby on Rails there is a gem called “barby” which generates the barcode with various format.

Here is an example to create barcode using barby & Rails 2.3.8.

Step#1

Include the barby gems in your config/environment.rb file

config.gem'barby'
config.gem 'barby-chunky_png'
config.gem 'png''RubyInline'

Install the gems by running the commandrake gems:install. Restart the Rails server.

You might face problem to start the server after the gems installed.Comment out the gems “png” & “RubyInline” in the “config/environment.rb” to get the server started.

Step#2

Create a folder named “Barcodes” to store the barcode images in your “Public” folder.

Step#3

Add the below lines of code in your controller

require'barby'
'barby/outputter/png_outputter'

Step#4

The following method will generate the barcode images and store in the “/public/Barcodes” path. Place this method inside the controller.

The “symbology” is the format in which the barcode will be generated. Default is “Code128B”, If you want to generate in different format you can set the “symbology” according to it.

def generate_barcodes(data) # check to see if we don't already have this barcode image uri = CGI.escape(symbology) + '_' + CGI.escape(data) + '.jpg' fname = RAILS_ROOT + '/public/Barcodes/' + uri #fname = '/var/www/html/arc_cloud/arcdevelopment/' + uri
 
# if the barcode image doesn't already exist then generate and save it
if ! File.exists?(fname)
 
str = 'Barby::'+symbology+'.new("'+data+'")'
 
begin
barcode = eval str
rescue Exception => exc
barcode = Barby::Code128B.new(data) # fall back to Code128 type B
end
 
File.open(fname, 'w') do |f|
f.write barcode.to_jpg
end
 
end
uri
end

Step#5

Following lines of code will call to generate your dynamic barcode
generate_barcodes(@item_id)

Step#6

To show the Barcode images call the following lines of code

<img src="/Barcodes/<%= @job_info.job_number %>.jpg" >

Creating an Engine on Refinery CMS

Refinerycms

‘Engines’ are nothing but ‘plug-ins’ which adds up extended functionality to the existing Refinery application. Engines installs in the “vendor/extensions” folder in a refinery app.

Engines will create a tab in the Admin panel of the Refinery CMS to control the information on the engine.This example demonstrates creating an engine in an existing refinery app. The environments used are Ruby 1.9.3, Rails 3.2.8 & Refinery cms 2.0.8.

Step#1

To create an engine, just execute the below command

rails generate refinery:engine engine_name attribute:type attribute:name

NB: The engine name should be in singular which will generate the structure in plural form.
For example we want a FAQ engine for our CMS which will be controlled by CMS admin

rails generate refinery:engine MyFaq question:string answer:text

Running the above command will create a new folder “extensions” under “vendor” directory and in the “extensions” the new engine “my_faqs” will be created.

Step#2

After that run the below commands to make it executable

bundle install
rails generate refinery:my_faqs
rake db:migrate
rake db:seed

Step#3

Restart the server to get the effect. You will find the new tab “My Faqs” has been added both in the menu section of the user section and admin section.

Login as Admin to manage your FAQs

How to customize an engine during creation?

Creating the engine with a namespace

rails g refinery:engine MyFaq title description:text --namespace FAQ

Creating the engine by skipping the frontend pages

It will add menu and form page in the admin section only. User section will be omitted

rails g refinery:engine MyFaq title description:text --skip-frontend

Customizing Error Messages In RAILS

In every application regardless of its complexity we require to customize error messages to make more sense. There are several ways to achieve it in Rails 3 and in Rails 2.3.x which are mentioned specifically and that can be handled either in models or controllers or helpers.

Solution# 1:

If it is needed to be handled in model and message need to be have customized instead of the attribute name. Like if the attribute name is “name” but you want to display messages “Employee name cannot be blank” then we have to install “custom-err-msg” plug-in.

This plugin gives you the option to not have your custom validation error message prefixed with the attribute name. Ordinarily, if you have, say:

validates_acceptance_of : terms, :message => 'Please accept the terms of service'

You’ll get the following error message: Terms Please accept the terms of service

This plugin allows you to omit the attribute name for specific messages. All you have to do is begin the message with a ‘^’ character. Example:

validates_acceptance_of :accepted_terms, :message => '^Please accept the terms of service'

step# 1

To install the ”custom-err-msg” plug-in you have to use the command.

“ruby script/plugin install https://github.com/gumayunov/custom-err-msg.git”

If you are facing problem by installing the plugin then clone it and just copy the folder (”gumayunov-custom-err-msg-640db42”) inside “Vendor/plugin/” folder

step# 2

In view file just display it as mentioned below:

Similarly, it can use in other places like,

validates_presence_of :claim_no, :message => "^Work Order/Claim number cannot be blank!"

The plugin also lets you use procs instead of strings.

Example:

validates_acceptance_of :accepted_terms, :message => Proc.new {|service| "You must accept the terms of the service #{service.name}" }

The above plug-in usage can be avoided by declaring alias for each attribute as mentioned below.
You should have a file named config/locales/en.yml, if not simply create one. There you can add your own custom names.

en:
activerecord:
models:
order: "Order"
attributes:
order:
b_name: "Business Name"

This will replace your attribute “b_name” with “Business Name”

Your Order model in app/models/order.rb should look like:

class Order < ActiveRecord::Base
validates :b_name, :presence => true

The error message will be displayed like

Business Name cannot be blank

Solution# 3:

Another way is to define a method and an error message inside the method in the model.

Class Employee < ActiveRecord::Base
validate :zip_must_be_valid
def zip_must_be_valid
unless zip.map(&:valid?).all?
errors.add_to_base " zip code is invalid"
end
end
end

We can also customize the error messages in Controllers.
Suppose “First Name” cannot be blank to be checked. Then use below code to check for it and show customized messages

if(params[:employee][:first_name].nil?)
flash[:error] = "First name should not be blank.n"
end

Subsequently, if it is required to add other messages to the above for other attributes then it can be written as,

if(params[:employee][:address].nil?)
flash[:error] += Address should not be blank.n"
end

Solution# 5

Customization of error messages can be done in controllers by adding messages to the existing error object’s method “add_to_base”.

if email_data[:"email_no_#{i}"] != "" && email_data[:"email_no_#{i}"] !~ /^([^@s]+)@((?:[-a-z0-9]+.)+[a-z]{2,})$/i
valid_params = false
@company_info_new.errors.add_to_base( "Invalid Email Id!" )
End

In views it can be displayed by writing below code:

0 %>
nil, :message => nil >

Solution# 6

The customization that can be handled in views using

“error_message_on” helpers (Rails 2.3.8)”

In case you wish to show one error message in a specific location that relates to a specific validation then use “error_message_on” helper. You might have used “error_message_on” to display field-specific error messages. Here is an example that would display an error message on a name field:

Solution# 7

You can also use “error_message_on”(Rails 2.3.8) to display non-field-specific error messages.

class User < ActiveRecord:Base
validate :user_is_active
private
def user_is_active
if self.is_active != true
errors.add : user_is_active, 'User must be active to continue'
end
end
end

Now, to display this custom validation error message with “error_message_on”, we simply need to reference “:user_is_active” when we call the helper. Consider this implementation:

Solutions# 8

class User < ActiveRecord::Base validates_presence_of :email validates_uniqueness_of :email validates_format_of :email, :with => /^[wd]+$/ :on => :create, :message => "is invalid"
end

In Rails 3 it’s possible to call a validate method and pass it a hash of attributes to define the validations instead of defining each validation separately as mentioned above.
/app/models/user.rb

class User < ActiveRecord::Base validates :email, :presence => true,
:uniqueness => true,
:format => { :with => /^([^@s]+)@((?:[-a-z0-9]+.)+[a-z]{2,})$/i }
end

In the User model we’re still validating that the field has a value and that the value is unique. For validating the format there are a number of options we can pass so we use a secondary hash to define those.

We can supply any number of validations for an attribute with a single command. While this is useful it can become cumbersome if there are a large number of validations but for most situations, it works nicely.

We can make the “:format” option more concise and clean it up a little. We often want to validate email addresses and having the same long regular expression in each validator is a little ugly and introduces repetition into the code. We can extract this out into a separate validation by creating a new class in our application’s /lib directory. We’ll call the file email_format_validator.rb.

class EmailFormatValidator < ActiveModel::EachValidator
def validate_each(object, attribute, value)
unless value =~ /^([^@s]+)@((?:[-a-z0-9]+.)+[a-z]{2,})$/i object.errors[attribute] << (options[:message] || "is not formatted properly")
end
end
end

The EmailFormatValidator class inherits from ActiveModel:: EachValidator. We have to define one method in the class “validate_each”, that takes three parameters called object, attribute and value. The method then checks that the value matches the regular expression we’re using to validate an email address and if not it will add the attribute to the objects errors.

We can use this technique to define any kind of validation we like. Now that we have our custom validator we can update the validator in the “User” model to use it.
/app/models/user.rb

class User < ActiveRecord::Base
validates :email,
:presence => true,
:uniqueness => true,
:format => { :with => /^([^@s]+)@((?:[-a-z0-9]+.)+[a-z]{2,})$/i }
end

Having an email_format key in the “validates” hash means that the validator will look for a class called email_format_validator and passes the validation behavior into the custom class that we just wrote.
If we try to create a new user now and enter an invalid email address we’ll see the expected error message.

If you have some trick to share, do it in the comments.

Polymorphic Associations in Rails3

ror31In polymorphic associations, a model can belong to more than one model, on a single association.

Here is an example where a model is associated with two other models in Rails3. For example we have Events and Article model which have comments. So the “Comment” model is common between the “Event” and “Article” model. Here are the steps to implement the polymorphic association between these three models.

Step#1
Let’s create a resource “Comment” by rails generator.

rails g scaffold Comment content:text

Step#2

Add associations in the models as below

Comment model:

class Comment < ActiveRecord::Base
attr_accessible :commentable_id, :commentable_type, :content
belongs_to :commentable, :polymorphic => true  #Now, it is acted as polymorphic
end

Event model:

class Event < ActiveRecord::Base
attr_accessible :name
has_many :comments, :as => :commentable
end

Article model:

class Article < ActiveRecord::Base
attr_accessible :name
has_many :comments, :as => :commentable
end

Step#3

Add the following attributes in the migration files of the comment model

Look for newly created file under “db/migrate” folder

class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.text :content
t.references :commentable, :polymorphic => true
t.timestamps
end
end
end

Then execute rake db: migrate in the command line

Step#4

Add nested resources inside the “config/routes.rb” file

resources :events  do
resources :comments
end
resources :articles do
resources :comments
end

Step#5

Add link to add new comments in view page of article and events as follows

In “/app/views/events/show.html.erb”

<%= link_to 'New comment', new_event_comment_path(@event)  %>

In /app/views/articles/show.html.erb

<%= link_to 'New comment', new_article_comment_path(@article)  %>

Step#6

Changing the form_for tag in new comment page

In “/app/views/comments/_form.html.erb”

Before

<%= form_for (@comment) do |f| %>

After

<%= form_for [@commentable, @comment] do |f| %>

Add following codes in both “Articles” & “Events” controllers to get the comments individually

In “/app/controllers/events_controller.rb”

def show
@event = Event.find(params[:id])
@comments= @event.comments #added to view all the comments for the selected event
respond_to do |format|
format.html # show.html.erb
format.json { render json: @event }
end
end

In “/app/controllers/articles_controller.rb”

def show
@article = Article.find(params[:id])
@comments= @article.comments #added to view all the comments for the selected article
respond_to do |format|
format.html # show.html.erb
format.json { render json: @article }
end
end

Step#8

Add the following codes to “Comments” controller to creating a comment

In “/app/controllers/comments_controller.rb”

class CommentsController < ApplicationController
def new
@commentable = find_commentable
@comment = Comment.new
end
def create
@commentable = find_commentable
@comment = @commentable.comments.build(params[:comment])
if @comment.save
flash[:notice] = "Successfully created comment."
redirect_to :id => nil
else
render :action => 'new'
end
end
 
private
 
def find_commentable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
nil
end
end

Now the comment model will work as a polymorphic association between article and event model.