How to map irregular database tables with rails models

Rails specifies standard conventions while creating models, controllers, migrations ( database tables ).

Conventions for creating database tables

1. Table name should be plural

2. id field must be primary_key for table.

3. foreign_key  must be like <model_name>_id i.e. post_id, site_id

Conventions for creating models & Controllers
1. Model name must be singular and controller name should be plural.
Although rails have some standard defined, sometimes it becomes quite necessary to map rails models with non- standard database tables.
1. Table mapping

class Review < ActiveRecord::Base
# Here comments is name of database table
set_table_name :comments
end

2. Set primary key ( other than rails standar ‘id’ primary_key )


class Review < ActiveRecord::Base
# It assumes "reviews" as table in database
# Below line indicates reviews table contains column_name "reviewId" which is a primary_key
set_primary_key :reviewId
end

3. Foreign key association


class Review < ActiveRecord::Base
# Below line indicates reviews table contains column_name 'RatingId' which is foreign_key to primary_key
# of 'ratings' table.
# It can be applied to any associan type [ has_one, has_many, belongs_to, has_many_through ]
belongs_to :rating, :class_name => "SiteUser", :foreign_key => "RatingId"
end

4. Model association ( non-standard model name )

class Review < ActiveRecord::Base
# Below line indicates reviews table contains column_name 'UserId' which is foreign_key to primary_key
# of model with class_name 'SiteUser'
belongs_to :user, :class_name => 'SiteUser', :foreign_key: => 'UserId'
end

Advertisements

About sandipransing

Web Developer #ruby #rails #JS
This entry was posted in Ruby on Rails and tagged , , . Bookmark the permalink.

2 Responses to How to map irregular database tables with rails models

  1. Gautam Rege says:

    If is use "set_primary_key :reviewId" in my Class Review model, how do I access the object ?What will object#id return? I believe object#id will take the primary key reviewId .. can you confirm this?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s