I’ve been trying to create web app in Ruby on Rails, which would collect menu for different restaurants and show it in my app. I’d like to create many-to-many association, but I’m a little confused there. I’ve googled many-to-many relationship and read about HABTM or has_many/belongs_to, still a bit confused.
My classes:
restaurant = {name}
menu = {name, price}
And join table:
menu_restaurant = {date}
I’m confused here. I’ve read that I can’t use HABTM with extra values in join table. And also I should not have model for join table using HABTM.
My current models:
app/models/menu.rb
class Menu < ActiveRecord::Base
attr_accessible :cenaStudent, :name
has_many :restaurants, dependent: :destroy
validates :priceStudent, presence: true
validates :name, presence:true
end
app/models/restaurant.rb
class Restaurant < ActiveRecord::Base
attr_accessible :name
has_many :menus, dependent: :destroy
validates :name, presence: true
end
app/models/menu_restaurant.rb
class MenuRestaurant < ActiveRecord::Base
attr_accessible :date
end
and these are my db tables
db/migrate/{timestamp}_create_restaurants.rb and similar {…}menu.rb
class CreateRestaurants < ActiveRecord::Migration
def self.up
create_table :restaurants do |t|
t.string :name
t.timestamps
end
end
def self.down
drop_table :restaurants
end
end
db/migrate/{timestamp}_create_menus_restaurants.rb
class CreateMenusRestaurants < ActiveRecord::Migration
def up
#create the association table
create_table :menus_restaurants, :id => false do |t|
t.integer :menu_id, :null => false
t.integer :restaurant_id, :null => false
t.date :date
end
#add index
add_index :menus_restaurants, [ :menu_id, :restaurant_id]
end
def down
remove_index :menus_restaurants, :column => [ :menu_id, :restaurant_id]
drop_table :menus_restaurants
end
end
What relationship in ruby on rails whould I use? What models do I need?
And I have a second question related RoR MVC architecture. I am going to write it here since it’s related.
I created a function in ruby that downloads pdf file containing menu list. Parses menu name and price. Restaurant name is matched with pdf file. So I have data I need to insert them into db. How do I do that and where? I guess some parts should be in controller and function should be in lib directory? It’s my first app using any architecture.
It’s also my first stackoverflow question, hope I didn’t forget anything.
I think you are almost there, your migrations and models seem ok except for dealing with the join table :menu_restaurants.
I have altered your models for so that the join table hooks everything up
Also I think your join table should be called menu_restaurants (singular on the word menu)