ruby-on-rails - rails : Different Controller behaviour depending on route

标签 ruby-on-rails parameters many-to-many params routes

我正在寻找解决以下情况的最佳实践:

我有一个“加法”模型,它应该与其他一些模型多对多关联。

例子:

# 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

两条路由都导致相同的 Controller 操作,即 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

这是处理该问题的正确方法吗?它工作得很好,但我不确定这是 rails 方式......
感谢您的回答!

最佳答案

叹气切换到答案空间,这样我至少可以添加回车符并使代码不愚蠢。

我同意 fl00r 的回答,但要补充的是,您需要这样实例化对象:

@type = params[:type] 
@obj = @type.constantize.find(params["#{type}_id"])
@additives = @obj.additives 

关于ruby-on-rails - rails : Different Controller behaviour depending on route,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5948444/

相关文章:

ruby-on-rails - 你如何撤消回滚(前滚?)

ruby-on-rails - 为什么即使条件为真,拒绝也不能处理我的哈希?

Spring 和 jtds.jdbc.Driver 参数

不使用模板参数的 C++ 模板类方法

vba - 尝试使用 VBA 在 Access 中打开记录集时出现 "Too few parameters error"

attributes - 在 Pony ORM 中是否可以向多对多关系的中间表添加额外的属性?

php - Laravel 软删除在数据透视表中不起作用

jquery - 如何在 Rails select_tag 上显示 Font Awesome 图标

ruby-on-rails - 出现 "First argument in form cannot contain nil or be empty"错误

python - 通过第三个表排除多对多关系