Hello Folks,
Its been a long time since I’ve not written a post. Now, I realize that it’s time to share some useful snippet with all of you.
Recently, I got a chance to get my hands cleaned with Rails 4. So much is happening around Rails community and with the rapid development of Rails 4, I was finding it bit difficult to keep my momentum going.
Well, leave all this apart. Now, by putting some extra efforts my system is ready with:
Ruby 2.1 & Rails 4.1
In order to start with my first Rails 4 Application, I took HABTM Association (weird, isn’t it?). It came randomly into my mind. However, I will dig into other associations as well with time, but to start with let’s take HABTM association with example.
I assume most of you are aware what changes Rails 4 has introduced. If you’re new to Rails 4 or would like to re-visit the changes, here’s the most useful link I’ve found. Just take a look.
Once you’re sure about changeset in Rails4, let’s draw an example:
Prerequisites:
- Ruby 1.9.2+
- Rails 4.1.0+
- Traditional Database (MySQL/Postgres)
Key-Entities:
- Person Model
- Communtiy Model
- A Join Table
Defining the Relationships & creating tables:
| #{PATH_TO_APP}$ rails g model Person name:string email:string | |
| #{PATH_TO_APP}$ rails g model Community name:string description:text | |
| class Person < ActiveRecord::Base | |
| has_and_belongs_to_many :communities | |
| end | |
| class Community < ActiveRecord::Base | |
| has_and_belongs_to_many :persons | |
| end | |
| class CreatePeople < ActiveRecord::Migration | |
| def change | |
| create_table :people do |t| | |
| t.string :name, null: false | |
| t.string :email, null: false | |
| t.timestamps | |
| end | |
| end | |
| end | |
| class CreateCommunities < ActiveRecord::Migration | |
| def change | |
| create_table :communities do |t| | |
| t.string :name, null: false | |
| t.text :description | |
| t.timestamps | |
| end | |
| end | |
| end | |
| # {PATH_TO_APP}$ rails g migration CreateJoinTablePersonCommunity person community | |
| # invoke active_record | |
| # create db/migrate/20140708122358_create_join_table_person_community.rb | |
| class CreateJoinTablePersonCommunity < ActiveRecord::Migration | |
| def change | |
| create_join_table :people, :communities, column_options: {null: true} do |t| | |
| # t.index [:person_id, :community_id] | |
| # t.index [:community_id, :person_id] | |
| end | |
| end | |
| end |
For rest of the code-flow (controllers, views) you can download the zip of the application from my GitHub page, run it on your local and see Rails4 HABTM in action.
Happy Coding 🙂

Leave a Reply