【发布时间】:2011-08-22 08:24:32
【问题描述】:
我正在寻找解决以下情况的最佳做法:
我有一个“加法”模型,它应该与其他一些模型多对多关联。
例子:
# Meal-Model
has_and_belongs_to_many :additives
# Offer-Model
has_and_belongs_to_many :additives
# Additive-Model
has_and_belongs_to_many :meals
has_and_belongs_to_many :meals
路由嵌套如下:
resources :offers do
resources :additives
end
resources :meals do
resources :additives
end
所以我得到这样的网址:
/offers/123/additives
/meals/567/additives
两条路由都指向同一个控制器操作,即additives#index。在 AdditivesController 中,我检查参数是否可用于选择要获取的数据:
class AdditivesController < ApplicationController
before_filter :offermealswitch
# GET /restaurants/1/meals/123/additives
# GET /restaurants/1/offers/123/additives
def index
@additives = @additivemeal.additives
end
def offermealswitch
if params.has_key?(:meal_id)
@additivemeal = Meal.find(params[:meal_id])
@type = "Meal"
elsif params.has_key?(:offer_id)
@additivemeal = Offer.find(params[:offer_id])
@type = "Offer"
end
end
end
这是处理该问题的正确方法吗?它工作得很好,但我不相信这是轨道方式...... 感谢您的回答!
【问题讨论】:
-
我认为您的解决方案非常好,直到您的
offermealswitch不太复杂。但你也可以在你的路线中通过type -
好吧,我找到了保存
@type实例变量的方法:当我需要在控制器中了解或查看实际处理的类型时,我检查@meal.class == Meal或@meal.class == Offer。只要它这么简单,对我来说似乎就是一个很好的解决方案。
标签: ruby-on-rails parameters many-to-many params routes