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.

Facebook Integration in Rails3 using ‘omniauth’ gem

feature11. Create a Facebook Application by using your ‘Facebook Developer account’
2. Get the ‘App ID’ and ‘App Secret’ of your created application

Add following gems to your Gemfile

  • gem ‘omniauth’
  • gem ‘omniauth-facebook’

Run ‘bundle install’

Create a middleware file named ‘omniauth.rb’ in ‘config/initializers’ path

Rails.application.config.middleware.use OmniAuth::Builder do
provider :facebook, ENV['FACEBOOK_KEY'], ENV['FACEBOOK_SECRET'],
{:scope ≥ 'email, read_stream, read_friendlists, friends_likes, friends_status, offline_access, publish_stream'}
end

This will hold the facebook_app_key and facebook_secret_key with permissions

Set your custom callback url in routes

match '/auth/:provider/callback', :to ≥ 'sessions#create' match '/auth/failure', :to ≥ 'sessions#failure'

Write the following codes in the Sessions Controller

def create
auth_hash = request.env['omniauth.auth'] # Got The precise information from facebook
if  !auth_hash.nil?
@user = User.find_or_create_from_auth_hash(auth_hash)
self.current_user = @user
redirect_to '/'
end
end
def failure
flash[:notice] = "Sorry, but you didn't allow access to our app!"
redirect_to '/'
end

Write the following code in your view page. You can use a custom image for the Facebook like ‘facebook.png’.

<%=link_to image_tag('/images/facebook.png'),
"/auth/facebook" %>

How to use Nested Attributes in Rails 3 Forms

For example, say we want to add multiple addresses(attributes) having many fields inside a create/edit employee form

Step# 1

  •         Create a model named Employee
  •         Create another model named Address
  •         Add the following relationship in Employee model
class Employee < ActiveRecord::Base
has_many :addresses, :dependent => :destroy
accepts_nested_attributes_for :addresses, :reject_if => lambda { |a| a[:city].blank? }
end
  •    Nested attribute form rejects if the city field of the address is blank

Step# 2

  •        In Employees controller add the following in the “new” action
def new
@employee = Employee.new
@employee.addresses << Address.new
end

Step# 3

  •         In the view file add the following inside the form attribute
<%= form_for @employee, :html => { :multipart => true, :id => 'new-employee' } do |f|
<%= f.label :name, 'Name' %>
<%= f.text_field :name %>
 
<% end %>

New iPhone 5 Is Big With A Small Wow Factor

Apple has unveiled its most awaited iPhone, the iPhone 5 in the launch event at Yerba Buena Center for the Arts in San Francisco. As soon as Apple CEO Tim Cook winded up his updated product metrics talk on the stage. Marketing chief Phil Schiller went up to introduce the new product and its features.

With iPhone application development on the rise and Apple winning the recent patent case, iPhone 5 has gained enough hype among iPhone lovers around the world.

As you try to find the differences between iPhone 5 and iPhone 4S, you’ll find a lot. The iPhone 5 is much bigger and more than 15% thinner than the iPhone 4S.

Never miss an update from us. Join 10,000+ marketers and leaders.

With the body of Glass and Aluminum, its now much lighter weighing about 3.95 ounces in total. Some of the key features which are improved in this new iPhone are:

  • Retinal display stretched from 3.5 inches to 4 inches which gives users and iOS developers some extra space to play around
  • 8MP Camera with backside illumination, in-built panorama mode and smart noise filtering
  • Three in-built microphones for improved in-voice assistant Siri
  • Apple’s new A6 processor which is double fast than other processors
  • Long battery support; and it can stand more than 8 hours of 4G browsing
  • New dock connector called “Lightning” and designer earpods

After looking over these features, you can say that they are evolutionary, but you surely would be looking for a WOW factor which lacks in iPhone 5. Most of these technologies or features are somehow available with Android or other smartphones.

Apple has launched the iPhone 5 to give over the edge competition to companies like Samsung, and other seller in market. The new iPhone 5 will be on sale in nine countries from 21 September onwards. It will be reaching to 240 countries by this year end.

During the event some other Apple products like redesigned iTunes library & new iPod ranges are shown. With various product ranges and more than 7,00,000 apps in the iTunes library, Apple plays a key competitor in the smartphone market.

Andolasoft, one of the pioneers of iPhone application development has also opened its toolbox to explore on iPhone 5 and iOS 6. We’ve expert developers who work closely with you in an agile and innovative environment.

Successful Mobile App And Ruby On Rails Projects

Andolasoft is remarkable and energetic to start the ball rolling in numerous products in mobile application development and Ruby on rails development arena.

Among them Christmas Tree Puzzle game app, job management app for iOS. Also Social email reminder app, Social media Job portal app in RoR are getting used by lots of people everyday.

Some of our new projects are product based and we are focusing on the advance technology of mobile and web application development like IPhone, Android, RoR, PHP/CakePHP. Very soon we are going to launch/release some new apps those are under development and will available in the market very shortly. Check out our recent portfolio and domains and technologies. We’re also growing by increasing our team size. We’ve a team of dedicated and skilled developers and designers who’re helping Andolasoft to do the job perfectly in right time. Quality assurance is one of our aim for all projects with a quick turnaround period. Continuously we keep hunting and hiring right folks with mobile as well as web technologies. Please check out current job openings.

PhoneGap Developers: Develop PhoneGap Application in Just 30 minutes!

phonegap

What is PhoneGap:
PhoneGap is an application framework that is based on the open standards of HTML5 and allows PhoneGap developer to use common technologies (HTML, JavaScript and CSS) to build applications for multiple mobile platforms from a single code base.With PhoneGap you can:

1. Take advantage of HTML5 and CSS.
2. Use JavaScript to write your code.
3. Access Native Features of the supported platforms.
4. Deploy your application to multiple platform.
5. It works similarly to native applications without a browser frame around them.
6. The basic fundamental of PhoneGap is “Write Once, Compile in the Cloud and Run Anywhere”.

Development of Application using PhoneGap within 30 minutes

Prerequisite Software for Application Development

1. Eclipse Integrated Design Environment (IDE) to write code for the development.
2. Java Development Kit (JDK).
3. Android Software Development Kit (SDK) for developing Android Application.
4. Android Development Toolkit (ADT).This is a plug-in for Eclipse required for the Android Application.
5. Install the PhoneGap and add the plug-in in your eclipse.

Build the Application in PhoneGap

1. After the PhoneGap plug in added in your eclipse, you will find an icon in the eclipse tool bar. (refer Screenshot – 1)
1

(Screenshot -1)

2. On click of the icon you will get a “Create a PhoneGap for Android Project” page.(refer Screenshot-2)
3. Choose “Use Built-in PhoneGap – version1.1.0” under “PhoneGap Configuration” and choose “use PhoneGap example source as template for project” under “Project Contents” then click on next button.
2

(Screenshot -2)

4. Enter the “Project name” , select the “Build target” and enter the “Package name” and click on finish button.
5. A Project will be created in your eclipse. For directory structure of the project please refer (Screenshot -3).
3

(Screenshot – 3)

6. Inside the project many directories will be created and among them one directory called “asset” where all the html5,CSS and JavaScript resides.
7. Open the inbuilt html5 from “asset” folder and design a page where there will two input fields ie. “First Name” and “Last Name” and two buttons ie.“Submit” and “Clear”. On Click of “Submit” button it will display the user entered name with Hi as an output.
8. Then run the application. For output please refer (Screenshot – 4).
4

(Screenshot – 4)

Andolasoft is a leading PhoneGap app development company. If you are looking for expert PhoneGap app developer then contact us.