Saturday, 22 September 2012

HABTM relation: Adding Record


class Menu < ActiveRecord::Base
...
  has_and_belongs_to_many :items, :join_table=>"menus_items"
  ...
end




class Item < ActiveRecord::Base
  has_and_belongs_to_many :menus, :join_table=>"menus_items"
  ....
end

Joining Table:
Menus_items
menu_id
item_id

Question: Given the scenerio how will you add record into "menus_items" table?
Answer:

menu = Menu.find(params[:menu_id])
item = Item.find(params[:item_id] )
menu.items << item   # Pushing element to an array
-----------------DONE-------------------------

No comments:

Post a Comment