【问题标题】:Rails routing with namespaces and nested routes带有命名空间和嵌套路由的 Rails 路由
【发布时间】:2018-03-15 23:42:42
【问题描述】:

我有一个 email_template 模型,它有一个嵌套资源 moves 来处理将 email_template 从一个文件夹移动到另一个文件夹。

但是,我想在 :templates 命名空间中命名这些操作,因为我还有几个其他资源也是模板项。

由于我是命名空间,我不想在 URL 中看到 templates/email_templates/:id,我希望看到 templates/emails/:id

为了实现这一点,我有以下几点:

# routes.rb
namespace :templates do
  resources :emails do
    scope module: :emails do
      resources :moves, only: [:new, :create]
    end
  end
end

当我对电子邮件执行 CRUD 操作时,一切正常,因为它们只是使用 :id 参数。但是,当我使用嵌套的 moves 时,电子邮件的父 ID 一直显示为 :email_id 而不是 :email_template_id。我确定这是 Rails 的预期行为,但我试图弄清楚父 ID 是如何确定的。它是来自路由中资源名称的单数形式,还是以某种方式从模型中构建的?

我想使用templates/emails/:email_id/moves/new 是可以的,但在完美的世界中我更喜欢templates/emails/:email_template_id/moves/new,这样开发人员就可以清楚地知道它是email_template 资源,而不是email

# app/controllers/templates/emails_controller.rb
module Templates
  class EmailsController < ApplicationController
    def show
      @email_template = EmailTemplate.find(params[:id])
    end
  end
end

# app/controllers/templates/emails/moves_controller.rb
module Templates
  module Emails
    class MovesController < ApplicationController
      def new
        # Would prefer to reference via :email_template_id parameter
        @email_template = EmailTemplate.find(params[:email_id])
      end

      def create
        @email_template = EmailTemplate.find(params[:email_id])

        # Not using strong_params here to demo code
        if @email_template.update_attribute(:email_tempate_folder_id, params[:email_template][:email_template_folder_id])
          redirect_to some_path
        else
          # errors...
        end
      end
    end
  end
end

【问题讨论】:

    标签: ruby-on-rails routes nested


    【解决方案1】:

    您可以将参数自定义为:

    resources :emails, param: :email_template_id do
          ...
    end
    

    【讨论】:

    • 当我这样做时,我收到错误“缺少必需的密钥:[:email_id]”,当我查看参数哈希时:{"param"=&gt;:email_template_id, "controller"=&gt;"templates/emails/moves", "action"=&gt;"new", "email_id"=&gt;"1"}
    猜你喜欢
    • 2013-10-09
    • 2015-03-19
    • 2011-11-07
    • 1970-01-01
    • 2011-10-10
    • 2012-05-10
    • 2018-09-23
    • 1970-01-01
    • 2015-07-02
    相关资源
    最近更新 更多