2014-01-12 49 views
0

我非常新的轨道,我最近有一个问题.. 我做了一个登录页面看起来就像是:Ruby on Rails的 - 无路由匹配[POST]“/登录/指数”

<!DOCTYPE html> 
<div id="content"> 
    <form action="#" method="POST" id="login-form"> 
     <fieldset> 
      <p> 
       <label for="login-username">username</label> 
       <input type="text" id="login-username" class="round full-width-input" autofocus /> 
      </p> 
      <p> 
       <label for="login-password">password</label> 
       <input type="password" id="login-password" class="round full-width-input" /> 
      </p> 
      <!--<a href="dashboard.html" class="button round blue image-right ic-right-arrow">LOG IN</a> 
      <%= link_to "Add to your favorites list", '/login/index', { :class=>"button round blue image-right ic-right-arrow" } %>--> 
      <%= submit_tag "Login" %> 
     </fieldset> 
    </form> 
</div> <!-- end content --> 

这种观点下的应用程序/意见/登录/ index.html.erb 匹配控制器下的应用程序/控制器/ login_controller.erb,看起来像:

class LoginController < ApplicationController 
    def index 
    end 

    def login 
    end 

end 

和我的路由看起来像这样:

BonhamNew::Application.routes.draw do 

    get "login/index" 
    # The priority is based upon order of creation: first created -> highest priority. 
    # See how all your routes lay out with "rake routes". 

    # You can have the root of your site routed with "root" 
    root 'login#index' 
end 

当我点击了透过,我得到: 没有路由匹配[POST]“/登录/指数”

我知道它很基本的,但也许some1可以在这里给我一个忙吗?

谢谢!

回答

1

您应该创建一个额外的途径post "login/index"

+0

嗨,似乎工作,但现在当我点击按钮,我得到:在LoginController#索引ActionController :: InvalidAuthenticityToken什么可以导致该问题? – gal

+0

@gal,这是与你不使用'form_tag'助手,请参阅我的答案。 – amnn

1

你应该除了获取路线的路线添加到您的routes.rb文件post 'login/index'。这将确保表单不会导致错误,但保持原样,并将表单发送到login#index而不是login#login

此外,而不是明确使用HTML表单标记,使用帮助器form_tag。在rails中练习更好,并且允许使用浏览器可能不支持的HTTP方法,例如PUT和DELETE。它还添加了Rails需要的字段,以确保您的表单不会通过跨站请求发送。 (真实性令牌)

还要注意在同一页与上述form_tagtext_field_taglabel_tagpassword_field_tag助手。您应该习惯使用这些优先于原始HTML。

+0

你应该改正'post login/index'到'post'login/index'' – deiga

+0

哎呀,是的,谢谢,完成 – amnn

0

阅读resourceful routing in Rails。其中的示例仅为资源使用ActiveRecord模型,但您也可以在没有ActiveRecord模型的情况下创建一个。

可以将登录视为资源,其中创建登录不会创建数据库记录,而是将用户登录到应用程序中。

在你的routes.rb定义资源如下:

BonhamNew::Application.routes.draw do 
    resource :login, only: [:show, :create] 
end 

这将使你的控制器如下:

class LoginsController 
    def show 
    # Renders a page with the login form 
    end 

    def create 
    # Logs the user in, your old login action 
    end 
end 

通知默认控制器的名称是怎样的复数形式,LoginsController。如果你想奇异的名字,只需指定控制器来使用你的资源,如下所示:

resource :login, controller: 'login', only: [:show, :create] 

然后你的控制器看起来是这样的:

class LoginController 
    # actions 
end