加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails:不同的控制器行为取决于路由

发布时间:2020-12-17 02:10:57 所属栏目:百科 来源:网络整理
导读:我正在寻找解决以下情况的最佳做法: 我有一个“添加”模型,它应该是与其他一些模型相关的多对多模型. 例子: # Meal-Modelhas_and_belongs_to_many :additives# Offer-Modelhas_and_belongs_to_many :additives# Additive-Modelhas_and_belongs_to_many :me
我正在寻找解决以下情况的最佳做法:

我有一个“添加”模型,它应该是与其他一些模型相关的多对多模型.

例子:

# 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

两条路线都导致相同的控制器动作,即添加剂#index.在AdditivesController中,我检查params是否可用于选择要获取的数据:

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

这是处理这个问题的正确方法吗?它工作得很好,但我不是shure这是轨道方式……
谢谢你的回答!

解决方法

叹息切换到应答空间所以我至少可以添加回车并使代码不笨.

我同意fl00r的答案,但会补充说你需要实例化对象:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读