Insert record in table entity-relationship

I’m brazilian, so, sorry for English…

I’m learning Ruby on Rails.

My project has 3 tables:

  • food
  • restaurant
  • food_restaurant

I can insert records in “food” and “restaurant” by default procedure:

f = Food.new :name => “Arroz”
f.save

r = Restaurant.new :name => “Madalosso”, :street => “Rua Tal, 290”
r.save

But, how I insert record in table “food_restaurant”.
“food_restaurant” dont have a object class, so I cant create a object
and save…
This table have 2 columns: “id_food” and “id_restaurant”

On Jan 24, 2012, at 8:36 AM, Bruno Furtado wrote:


f = Food.new :name => “Arroz”
f.save

r = Restaurant.new :name => “Madalosso”, :street => “Rua Tal, 290”
r.save

But, how I insert record in table “food_restaurant”.
“food_restaurant” dont have a object class, so I cant create a object
and save…

Did you set this up as a “has and belongs to many” relationship?

class Food > ActiveRecord::Base
has_and_belongs_to_many :restaurants

end

class Restaurant > ActiveRecord::Base
has_and_belongs_to_many :foods

end

If you declared that in your food and restaurant models, and renamed
that join table as foods_restaurants, you would get the join for “free”,
just by loading the relationship in your controller:

@restaurant = Restaurant.find(params[:id])
@foods = Food.where(:foo => ‘bar’)
@restaurant.foods = @foods

when you save @restaurant, a new set of records will be created in
foods_restaurants, keying that particular restaurant to those N foods.

This table have 2 columns: “id_food” and “id_restaurant”

These have to be named food_id and restaurant_id

Walter

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs