【问题标题】:No route matches [POST] "/users/new"没有路线匹配 [POST] "/users/new"
【发布时间】:2014-12-17 16:33:22
【问题描述】:

请帮我解决这个错误。

错误: 没有路线匹配 [POST] "/users/new"

我的代码 sn-ps 是:

视图/用户/index.html.erb

<h1>This is Registration page..</h1>
<div class="sign">
<%= button_to "Registration",{:controller => "users", :action => "new",method: :get} %>
<%= button_to "Login",action:"login" , method: :get %>
</div>

config/route.rb

    Rails.application.routes.draw do
      root "users#index"
      get "users/new" => "users#new"
      get "users/login" => "users#login"
      #get "users/new" => "users#new", as: new_user
      #get "users/login" => "users#login", as: login_user
   end

请帮我设置路由文件。

【问题讨论】:

  • &lt;%= button_to "Registration",{:controller =&gt; "users", :action =&gt; "new",method: :get} %&gt;更改为&lt;%= button_to "Registration", new_user_path %&gt;
  • 显示你的用户控制器
  • 我也可以建议你在路由中使用 CRUD 操作resources :users

标签: ruby-on-rails ruby regex ruby-on-rails-3


【解决方案1】:

首先通过命名路线让您的生活更轻松:

# in config/routes.rb
Rails.application.routes.draw do
  root "users#index"
  get "users/new"   => "users#new",   :as => :new_user
  get "users/login" => "users#login", :as => :login
end

进一步注意:method 参数是第三个(不是第二个)参数的一部分:

<%= button_to "Registration", new_user_path, :method => :get %>
<%= button_to "Login", login_path, :method => :get %>

或者没有命名路线:

<%= button_to "Registration", { :controller => "users", :action => "new" }, :method => :get %>
<%= button_to "Login", { :action => "login" }, method => :get %>

注意大括号。

【讨论】:

    【解决方案2】:

    button_to 的默认方法类型是 POST。你有posts_new_path 作为类型GET

    所以最好使用 link_to 而不是 button_to 并使用 css 将这些链接转换为看起来像按钮。

    <%= link_to "REGISTER",users_new_path%>
    

    css 应该是这样的:

    a:link, a:visited {
      display: block;
      width: 6em;  
      padding: 0.2em;
      line-height: 1.4;
      background-color: #94B8E9;
      border: 1px solid black;
      color: #000;
      text-decoration: none;
      text-align: center;
    }
    
    a:hover {
     background-color: #369;
     color: #fff;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-05
      相关资源
      最近更新 更多