Reputation: 109
im working on this model association class assignment. the basic association works, but im having issue with the "category"-page view.
Category Page Output should be (/categories/1)
rules: - dish belongs to one category - same dish can be in multiple restaurants
class Category < ActiveRecord::Base
has_many :dishes
end
class Dish < ActiveRecord::Base
belongs_to :category
end
class Restaurant < ActiveRecord::Base
has_and_belongs_to_many :dishes
end
class DishRestaurant < ActiveRecord::Base
has_many :restaurants
has_many :dishes
end
Category Controller
def show
@category = Category.find(params[:id])
@dishes = @category.dishes
// RESTAURANT TITLE ??
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @category }
end
Category View: <%= debug @dishes %>
any hint would be helpful.
thanks
pete
Upvotes: 0
Views: 141
Reputation: 10907
Define you models properly:
class Dish < ActiveRecord::Base
belongs_to :category
has_and_belongs_to_many :restaurants
end
class Restaurant < ActiveRecord::Base
has_and_belongs_to_many :dishes
end
This would use the implicit join table names "dishes_restaurants". You only need a join model is you store some join specific information, like price of the dish in the restaurant. In which case you models should be like:
class Dish < ActiveRecord::Base
belongs_to :category
has_many :dish_restaurants
has_many :restaurants, through => :dish_restaurants
end
class Restaurant < ActiveRecord::Base
has_many :dish_restaurants
has_many :dishes, through => :dish_restaurants
end
class DishRestaurant < ActiveRecord::Base
belongs_to :restaurant
belongs_to :dish
end
Whatever approach you follow, you can do dish.restaurants
to retrieve the list of the restaurants which serve the dish.
Upvotes: 1