【问题标题】:Rails: Different Controller behaviour depending on routeRails:不同的控制器行为取决于路线
【发布时间】: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


【解决方案1】:

sigh 切换到答案空间,这样我至少可以添加回车并使代码不笨。

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

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

【讨论】:

  • 我被认为只是一般,所以我错过了代码不起作用:)
  • 这也经常发生在我身上:)
  • 感谢您的回答! Constantize 对我来说是新的。但我认为我保留了我的解决方案,以使 URL 尽可能简单。我的 URL 中已有内容的另一个类型属性对我来说似乎是多余的。
【解决方案2】:

编辑关于@Taryn East

resources :offers do
  resources :additives, :type => "Offer"
end
resources :meals do
  resources :additives, :type => "Meal"
end

class AdditivesController < ApplicationController
  before_filter :find_additive

  def index   
    @additives = @additive.additives    
  end

  private
  def find_additive
    @type = params[:type]
    @additive = @type.constantize.find([@type, "id"].join("_")) # or "#{@type}_id", as you wish
  end
end

【讨论】:

  • 那需要是:@type = params[:type].constantize ; @obj = @type.find(params["#{type}_id"]) ; @additives = @obj.additives
  • @Taryn East,你可以看到作者需要这个@type 是一个字符串,所以我们不能将它常量化,或者我们需要将它作为一个字符串返回。但这实际上并不重要。是的,你对我的错误是对的:)
  • 已在我自己的“答案”中添加和更新(因此格式不会那么糟糕)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多