Rails form_for(新)重定向提交后显示

时间:2015-10-27 21:05:55

标签: ruby-on-rails forms devise

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

<%= 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" %>
   

2 个答案:

答案 0 :(得分:1)

  

&#34;管理员&#34; 客户索引。

如果是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作为样式机制

我看到有人一直使用<p><br />进行样式;这是错的。您有一个完整的CSS管道来设置表单样式:

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

您可以在此处查看此操作:http://jsfiddle.net/qgk4dy3j/

答案 1 :(得分:0)

您是否在clients_controller.rb方法new上创建了一个新的客户端实例? 同样在您的表单上我相信<%= form_for @client do |f| %>就足够了 例如:

 def new
    @client = Client.new
  end

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