【问题标题】:Rails form_for (new) redirect to show after submissionRails form_for(新)重定向以在提交后显示
【发布时间】:2015-10-27 21:05:55
【问题描述】:

我正在使用管理会话来创建一个新客户端。当我提交表单时,我需要将其重定向到该客户端显示页面,但此时 @client id 等于 nil。我正在使用设计进行身份验证,因此当管理员创建客户端时,它会直接进入客户端主页。我需要转到“管理员”客户端索引。感谢您的帮助。

<%= form_for @client, :url => client_path(@client) do |f| %>

  <p> <%= f.label :name, "Empresa" %> <%= f.text_field :name %></p>
  <p> <%= f.label :email %> <%= f.text_field :email %> </p>
  <p> <%= f.label :password %> <%= f.text_field :password %> </p>
  <p> <%= f.label :contact %> <%= f.text_field :contact %></p>

  <%= f.submit "Create", :class => "btn btn-primary" %>

【问题讨论】:

    标签: ruby-on-rails forms devise


    【解决方案1】:

    “管理员” 客户端索引。

    如果是namespaced,您需要处理所有对象和路径引用中的命名空间:

    <%= form_for [:admin, @client] do |f| %> #-> sends to admin/clients#create
    

    这假设您使用的是命名空间 Admin::ClientsController 控制器:

    #config/routes.rb
    namespace :admin do
       resources :clients, only: [:new, :create, :index]
    end
    
    #app/controllers/admin/clients_controller.rb
    class Admin::ClientsController < ApplicationController
       before_action :authenticate_user!
    
       def index
          @clients = Client.all
       end
    
       def new
          @client = Client.new
       end
    
       def create
          @client = Client.new client_params
          @client.save
       end
    
    end
    

    顺便说一句,您需要确保您没有使用 HTML 作为样式机制

    我看到人们一直在使用&lt;p&gt;&lt;br /&gt; 进行造型;这是错的。你有一个完整的 CSS 管道来设置你的表单样式:

    #app/assets/stylesheets/application.css
    form input {
       margin: 10px 0;
    }
    

    你可以在这里看到这个:http://jsfiddle.net/qgk4dy3j/

    【讨论】:

    • 感谢 Rich,我刚刚开始使用它。也感谢 CSS 推荐(我只是在测试,所以我添加了这些标签以获得清晰的视图)但是我会记住它。
    【解决方案2】:

    你是否在 clients_controller.rb 方法 new 上创建了一个新的客户端实例? 在你的表格上我相信&lt;%= form_for @client do |f| %&gt; 就足够了 示例:

     def new
        @client = Client.new
      end
    
      def create
        @client = Client.new(client_params) 
        if @client.save
          redirect_to @client
        else
          render :new
        end
      end
    

    【讨论】:

    • 感谢泰雷兹,但它不会发送到客户端控制器,因为我正在使用设计进行身份验证。因此,当管理员创建客户端时,它会直接进入客户端主页。我想去“管理员”客户索引。我希望我很清楚
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    • 2014-09-05
    • 2016-01-09
    • 1970-01-01
    • 2019-08-21
    • 2013-06-29
    相关资源
    最近更新 更多