0

I have some troubles with routes in Rails 4 (rusty Rails user). I have the following routes for my Session controller:

controller :sessions do
  get 'login' => :new
  post 'login' => :create
  delete 'logout' => :destroy
end

get "sessions/create"
get "sessions/destroy"

And I have a form that looks like this:

= form_tag do
  .form_container
    .field
      = label_tag :name, "Namn:"
      = text_field_tag :name, params[:name]
    .field
      = label_tag :password, "Lösenord:"
      = password_field_tag :password, params[:password]
    .actions
      = submit_tag 'Login', :class => "submit_button"

And my session#create action looks like this:

def create
  user = User.find_by(name: params[:name])
  if user and user.authenticate(params[:password])
    session[:user_id] = user.id
    redirect_to  root_path
  else 
    redirect_to login_url, alert: "Invalid user/password combination"
  end
end

And I get the following error:

No route matches [POST] "/login/create"

How should my routes look in this case?

4

1 回答 1

2

我一般有一个

resource :session
post 'login'    => 'sessions#create'
get 'login'    => 'sessions#new'

创造

     session POST   /session(.:format)                             sessions#create
 new_session GET    /session/new(.:format)                         sessions#new
edit_session GET    /session/edit(.:format)                        sessions#edit
             GET    /session(.:format)                             sessions#show
             PUT    /session(.:format)                             sessions#update
             DELETE /session(.:format)                             sessions#destroy
       login POST   /login(.:format)                               sessions#create
             GET    /login(.:format)                               sessions#new

之后,只需在需要的地方使用正确的网址

= form_tag login_path
  ...

这应该够了吧

于 2013-06-26T20:09:38.590 回答