Let’s say we have two model Photo and Album, and we like to attablish the many to many relationship between these two models. Here the whole process : 

  • Create Photo model like the following: 

class Photo < ActiveRecord::Base
# validate photo_id unique
validates_uniqueness_of :photo_id

# setup many to meny relationship with albums table
has_and_belongs_to_many :albums

end

 

  • Create Album model like the following: 

class Album < ActiveRecord::Base

has_and_belongs_to_many :photos

end

  • Have the migration for Albums_Photos table like the following: 

class CreateAlbumsPhotos < ActiveRecord::Migration
def change
create_table :albums_photos do |t|
t.references :photo, :null => false
t.references :album, :null => false

t.timestamps
end
add_index(:albums_photos, [:photo_id, :album_id], :unique => true)
end
end

  • After we create bridgetable, here is how we implement the many to many association

photo = Photo.find_by_photo_id(params[:photo_id])
album = Album.find(params[:album_id])
album.photos << photo

 

photo = Photo.find_by_photo_id(params[:photo_id])    album = Album.find(params[:album_id])    album.photos << photo