Roger
Roger

Reputation: 11051

Ruby on Rails Tutorial chapter 9

I am confused by the addition of [:session] to params. It also seems to break my website. Can someone please explain what this does for me?

class SessionsController < ApplicationController
  .
  .
  .
  def create
    user = User.find_by_email(params[:session][:email])
    if user && user.authenticate(params[:session][:password])
      sign_in user
      redirect_back_or user
    else
      flash.now[:error] = 'Invalid email/password combination'
      render 'new'
    end
  end
  .
  .
  .
end

Error message:

1) Authentication signin with invalid information Failure/Error: before { click_button "Sign in" } NoMethodError: undefined method []' for nil:NilClass # ./app/controllers/sessions_controller.rb:7:increate' # (eval):2:in click_button' # ./spec/requests/authentication_pages_spec.rb:18:inblock (4 levels) in '

EDIT 8/2

I believe the problem is related to a switch from form_for to form_tag. I lost the reference to sessions in the switch because I could not figure out how to properly include it. If anyone has any advice on this issue it would be most appreciated. I am wondering if there is a practical reason for wanting it to be params[:session][:email] instead or is it just for organization?

new.html.erb

<% provide(:title, "Sign in") %>
<h1>Sign in</h1>

<div class="row">
  <div class="span6 offset3">
    <%= form_tag sessions_path do %>

      <%= label_tag :email %>
      <%= text_field_tag :email %>

      <%= label_tag :password %>
      <%= password_field_tag :password %>

      <%= submit_tag "Sign in", class: "btn btn-large btn-primary" %>
    <% end %>

    <p>New user? <%= link_to "Sign up now!", signup_path %></p>
  </div>
</div>

Upvotes: 0

Views: 344

Answers (3)

Dougui
Dougui

Reputation: 7230

You can replace this in your view :

<%= form_for :session, :url => sessions_path do %>

  <%= label_tag :email %>
  <%= text_field_tag :email %>

  <%= label_tag :password %>
  <%= password_field_tag :password %>

  <%= submit_tag "Sign in", class: "btn btn-large btn-primary" %>
<% end %>

form_tag generate just an HTML form tag and form_for is used to describe something. All the inputs for a field of a form create with form_for will have a name like this : user_session[email]. So, when you submit the form, in your controller, you will have this : params[:user_session][:email].

Upvotes: 0

freeze
freeze

Reputation: 576

It brakes your code 'cos the params[:session] is nil I think and you trying to get [:email] from nil, what ofcourse should cause the exception. There should be some code in tutorial that defines params[:session] hash. Try to look better. To make your code stable you have to be sure that params[:session] is always defined or try to use ternar function params[:session] ? params[:session][:email] : ''

Upvotes: 0

Martin Lang
Martin Lang

Reputation: 353

Try removing the [:session] brackets, that worked for me

Upvotes: 1

Related Questions