File Uploading Through Paperclip in Rails 3.x

Rails3Paperclip is an easy file attachment library for Rails Applications. Attached files are saved to the file system, database or cloud and referenced in the browser by an easily understandable specification.

Here is an example to explain the image attachment for a user profile in an application. This example narrates about saving the image in the file system. However, the images can be saved in S3 bucket [Amazon Simple Storage Service, S3] or database.

Step#1

ImageMagick must be installed in the system and Paperclip must have access to it. ImageMagick is a software suite to create, edit, compose, or convert bitmap images. It can read and write images in a variety of formats. You can download it by visiting the following URL:

http://www.imagemagick.org/script/index.php

Step#2
Include the paperclip gem in your Gemfile

gem "paperclip"

Then run the bundler to install the gem

bundle install

Step#3
Add the fields for the image processing as below in your migration file

class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :photo_file_name
t.string :photo_content_type
t.string :photo_file_size
t.timestamps
end
end
end

Then run your migration files

rake db:migrate

Step#4

Modify the user model for cropping and save image in your system folder

has_attached_file :photo, :styles => { :small => "150x150>" },
:url => "/system/:attachment/:id/:style/:basename.:extension",
:path => ":rails_root/public/system/:attachment/:id/:style/:basename.:ex

Here you can specify the file path and the image size as per the requirement.

Step#5
Modify your view file to upload an image

<pre class="plain plain">&lt;%= form_for :user,:url =&gt; {:action =&gt; "create"}, :html =&gt; { :multipart =&gt; true } do |f| %&gt;
&lt;%= f.file_field :photo %&gt;
&lt;% end %&gt;</pre>

Step#6
Write the following code to display the image of a user

<%= image_tag @user.photo.url (:small)%>

Please stay connected with us by subscribing our email.
Also feel free to share your opinions in the comments section below:

How to Generate SEO Friendly URL in Rails 3.x

Rails3SEO friendly URLs are more important to make a page popular & search engines to crawl.

FriendlyId is the slugging and permalink plug-in for Ruby on Rails. It allows you to create pretty URLs and work with human-friendly strings.

The URLs created by slug are very useful for SEO. It is designed for generation of URL slug and history maintenance.

Steps to create Pretty URLs:

Step#1

Include gem in your Gem file:

gem 'friendly_id'

Then run bundle install.

Step#2

Modify your model on which you want the pretty URL:

extend FriendlyId
 
friendly_id :title, use: :slugged

Step#3

Add the slug column in your migration file to add it on the table

add_column :articles, :slug, :string

Then run

rake db:migrate

Now if you create an article with Title like “This is a demo title for testing”,
it will create a SEO friendly URL like “this-is-a-demo-title-for-testing” and will
save into the articles table under slug column.

Collecting Contacts Using Cardmagic-Contacts Pplug-in in Rails 2.3.8

Rails3

Cardmagic-Contacts is a rails plug-in which provides an interface to fetch contact list information from various email providers including Hotmail, AOL, Gmail, Plaxo, Yahoo and many more.

This example narrates how to extract contact list using Rails 2.3.8 and cardmagic-contacts plug-in

Step#1

  • Download the plug-in by running the command below to store the plug-in in the folder “vendor/plug-ins”

Windows

ruby script/plugin install git://github.com/cardmagic/contacts

Linux

ruby script/plugin http://github.com/cardmagic/contacts

Step#2

  • Write down the following code on the top of the controller class
require 'contacts'

Step#3

  • Pass the required gmail/yahoo/hotmail/AOL login & password from view
<div>
 
<div style="margin-left:25px;" >Invite <img src="../images/yahoo.JPG">Yahoo
 
Friends </div>
 
<div style="margin-left:25px;">Yahoo Email: <input type="text" name="email"
 
id="yahoo_email_id"></div>
<div style="margin-left:25px;">Password:   <input type="password"
 
name="email"  id="yahoo_pwd_id"></div>
 
<div style="margin-left:122px;margin-top:20px;"><input type="button"
 
value="Login" name="btn_submit" id="btn_submit" ></div>
 
</div>

Step#4

  • Create an action to fetch the list of contacts for a specific email id

def grab_contacts #Grab gmail contacts @gmail_contacts=Contacts::Gmail.new(login, password).contacts #or @gmail_contacts=Contacts.new(:gmail, login, password).contacts #Grab yahoo contacts @yahoo_contacts = Contacts::Yahoo.new(login, password).contacts #or @yahoo_contacts = Contacts.new(:yahoo, login, password).contacts #Grab hotmail contacts @hotmail_contacts =Contacts::Hotmail.new(login, password).contacts #or @hotmail_contacts = Contacts.new(:hotmail, login, password).contacts end

Step#5

  • Here is also alternate method to get the contacts by providing  email_id and password
any_mail = Contacts.guess(login, password).contacts

The “Contacts.guess” method will automatically concatenate the entire
address book from each of the successful logins. If the login and password is
working with multiple email accounts then it will grab the contacts from all accounts.

Step#6

  • Display the friends list in your view page
<table>
<th>
<td >Friends Name</td>
<td >Friends Email</td>
</th>
<tr>
<% @gmail_contacts.each do |contact| %>
<td><%=contact[0]%></td>
<td><%=contact[1]%></td>
<% end %>
</tr>
</table>

What is the Importance of Filters in Rails

Rails

In Ruby on Rails development, filters play a vital role. They are the methods executed ‘before’, ‘after’  or  ‘around’ a controller action.

For example, one filter might check to see if the user has the credentials to access that particular controller or action.

Filters are inherited, so if you set a filter on ‘ApplicationController’, it would run on every controller in your application.

Below is an example to explain how a filter can be used to restrict a non-logged in user to access specified actions in a controller

Step#1

  • In Application controller write the following block of code according to the requirement.
def user_login_required
 if !session[:username]
 flash[:notice] = "Oops you need to login!"
 redirect_to :controller => "user_sessions", :action => "new"
 end
end

Step#2

  • Now write the before_filter block in the controller you want to restrict the not registered users. You can also restrict particular actions of a controller by writing the action name.
class UsersController < ApplicationController
 before_filter :user_login_required, :only => [:profile]
 def profile
 [Your code block goes here]
 end
end

In the above block the ‘before_filter’ restrict the not registered user to access
the profile page and redirect them to login page. We can also restrict multiple
actions by writing like this

before_filter :user_login_required, :only => [:profile,:edit]

In this case the filter is applied to only these two methods of a particular controller.

before_filter :user_login_required, :except => [:index,:show]

In this case the filter is applied to all other actions except index and show
action of a particular controller.

If you write the before_filter block in the “ApplicationController” then the
filter will be applied to all the controllers.

Planning anything on Ruby on Rails? Talk to Andolasoft’s experts to get a clearer idea.

How to create a form page in Refinery CMS app

Refinerycms

Refinery is a powerful CMS based on Rails framework. It gives a fully generated site with admin control features. However, we can extend it to create our own customized forms like Job Inquiry, Contact Us etc… by following this tutorial. Here is the environment we have used on this tutorial.Ruby 1.9.3, Rails 3.2.8 & RefineryCMS 2.0.8

Step#1

Cd to refinerycms application

Execute the following command to get all the options & usages to create a form engine in refinery CMS

rails g refinery:form

Step#2

Execute the following command to create a form. Let’s create a Job Inquiry form

rails generate refinery:form job_inquiry name:string message:text job_type:radio brochure:checkbox qualification:select

Step#3

Run the following commands

bundle install
 
rails generate refinery:job_inquiries
 
rake db:migrate<code></code>
 
<code>rake db:seed<code>

ss

This will create a “job inquiry” engine in the “vendor/extensions” folder

Step#4
Add the “job type” and “qualification” data in the “/vendor/extensions/job_inquiries/app/models/refinery/job_inquiries/job_inquiry.rb” model. You can also add other fields as per your requirement.

module Refinery
module JobInquiries
class JobInquiry < Refinery::Core::BaseModel       self.table_name = 'refinery_job_inquiries'       attr_accessible :name, :message, :job_type, :brochure, :qualification, :position       acts_as_indexed :fields => [:name, :message]
# Add some validation here if you want to validate the user's input
# We have validated the first string field for you.
validates :name, :presence => true
JOB_TYPES = ["Freelance", "Fulltime", “Contract”]
QUALIFICATIONS = ["MCA", "MTECH", "BTECH"]
end
end
end

Step#5

Restart the rails server to get the effect

That’s it! We will have a fully functional Job Inquiry form attached in our refinery application. This will also add the following functionalities automatically.

  • Mail send feature to Admin after submitting the job inquiry form
  • Auto email respond functionality to the user after submitting the form
  • Adds Job Inquiry menu in the Admin side to manage auto email respond message, mail id change to get job inquiry
  • Adds an Inbox in the Job Inquiry Menu for Admin to manage all the forms submitted through the Job Inquiry form

SEE ALSO: Creation of a new Rails App using Refinery CMS

If you have any other tips or rules that you follow, let us know in the comments below.

How to install Devise in Rails 3.x

ror41-150x150Devise is a flexible authentication solution for Rails based on Warden. Devise handles authentication across the entire stack. It has the following features:

  • Rack based
  • MVC based on Rails engines
  • Allows you to have multiple roles (or models/scopes) signed in at the same time
  • Modularity concept: use just what you really need

It is composed of 12 modules:

  • Database Authenticatable
  • Token Authenticatable
  • Omniauthable
  • Confirmable
  • Recoverable
  • Registerable
  • Rememberable
  • Trackable
  • Timeoutable
  • Validatable
  • Lockable

Steps to install the Devise

Step#1

Add the following gem in your Gemfile

gem 'devise'

Then run

bundle install

Step#2

To invoke the Devise in your application, run the devise generator

 rails g devise:install

The generator will install an initialize, which describes all devise’s configuration options.

Step#3

Create a model “User” using devise to handle authentication.

rails g devise User

This generator creates a few interesting things like a file, a migration and a devise_for in route.

Step#4

Run the migration

rake db:migrate

Step#5

Devise provides some helper methods to recognize a user after sign in and default route paths for “sign in”, “sign up” and “sign out”

We can modify our ‘app/views/layout/application.html.erb’ file to allow us to “sign out”, “sign in” and “sign up” by writing the following block

<div>
<% if user_signed_in? %>
Signed in as <%= current_user.email %>. Not you?
<%= link_to "Sign out", destroy_user_session_path,:method => :delete %>
<% else %>
<%= link_to "Sign up", new_user_registration_path %> or
<%= link_to "Sign in", new_user_session_path %>
<% end %>
</div>

Configuring views

Since Devise is an engine, all its views are packaged inside the devise gem.

Get all the view files for devise by running the following generate command

rails generate devise:views

You can also configure the message language, mailer from address and other things by editing the devise config files as located in following locations

devise.en.yml – config/locales
 
devise.rb – config/initializers

Now you are done to use the app with authentication!