Posts

Showing posts with the label HABTM Association in Rails

has_and_belongs_to_many association in Rails 4

  has_and_belongs_to_many (HABTM) association in Rails 4 A has_and_belongs_to_many association directly creates a many-to-many connection between models. This blog will illustrate how to implement such relation in Rails3 using this example - if an application includes two models :- 1. Subject 2. Page Here each  Subject  can have many  Pages  and each  Page  can appear in many  Subjects . Following are the required steps for implementing such relation :- 1. Generate the models using the command rails g model  Subject rails g model  Page Note: you can add necessary attributes to the models. 2. Declare the models in this way class  Subject  < ActiveRecord::Base   has_and_belongs_to_many :pages  end class  Page  < ActiveRecord::Base   has_and_belongs_to_many :subjects end 3. On running  rake db:migrate  for these models, by default rails create a column  id  in it...