我正在处理这个模型关联类的分配。基本关联有效,但我对“类别” - 页面视图有疑问。
类别页面输出应为(/ categories / 1)
规则: - 菜属于一个类别 - 同一道菜可以在多家餐厅
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
类别控制器
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
类别视图: &lt;%= debug @dishes%&gt;
任何提示都会有所帮助。
感谢
皮特
答案 0 :(得分:1)
正确定义模型:
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
这将使用隐式连接表名称“dishes_restaurants”。您只需要一个连接模型即可存储一些连接特定信息,例如餐厅菜肴的价格。在这种情况下,您的模型应该是:
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
无论您采用何种方法,都可以dish.restaurants
检索提供菜肴的餐厅列表。