【问题标题】:Rails: Shallow route name with custom behaviourRails:具有自定义行为的浅路径名称
【发布时间】:2013-06-26 13:57:21
【问题描述】:

假设我有两个模型(Model1 和 Model2)共享同一个控制器,它们都有很多 Model3 实例。

如何实现在两个模型中嵌套 Model 3 并拥有路径:model_3_path(@model) 而不是 model_1_model_3_path(@model)model_2_model_3_path(@model)

我希望我的 model_3_path(@model) 函数看起来像这样:

def model_3_path(model)
  if model.is_a? Model1
    "/model1/#{model.id}/model3"
  elsif model.is_a? Model2
    "/model2/#{model.id}/model3"
  end
end

我目前的进度:

concern :three { resources :model3, shallow: true }
resources :model1, concerns: :three
resources :model2, concerns: :three, controller: :model1, except: [:index] # /model2 isn't permitted

我似乎找不到正确的方法...

【问题讨论】:

    标签: ruby-on-rails custom-routes nested-routes


    【解决方案1】:

    我找到了一个简单的解决方案:首先,我删除了model3中的shallow。通过打开帮助类并添加method_missing定义,这很容易实现:

    def method_missing(method, *args, &block)
      super unless /model3s?_(path|url|uri)$/ =~ method.to_s
      sub_string = nil
      if args.first.is_a? Model1
        substring = 'model1'
      elsif args.first.is_a? Model2
        substring = 'model2'
      end
      self.send(method.to_s.gsub('model3', "#{substring}_model3"), *args, &block)
    end
    

    可以自己定义每一个(new_model3_path、model3_path、edit_model3_path、model3s_path),但我发现这个更简洁。

    【讨论】:

      【解决方案2】:

      如果你想要一个没有指定它的父路径的路径,只需将它作为顶级路由,而不是问题。

      【讨论】:

      • 我确实希望他们指定他们的父母,我只希望命名路由是通用的,具体取决于传入的参数,可以是 Model1 或 Model2。请仔细阅读问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-11
      相关资源
      最近更新 更多