Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

NoMethodError in Devise::Session#new

I am creating a application for sending SMS online. I want to the sent messages list and the create new message form to be in one page. So i made some changes in app/controllers/messages_controller.rb:

       # GET /messages.json
    def index
      @messages = current_user.messages.all
 +    @message = current_user.messages.new
    end

    # GET /messages/1
 @@ -38,14 +39,10 @@ def create
             sms_text = sms_text + "\n" +"...Enviado de AngoRussia.com"
             response = nexmo.send_message({:to => @message.phone_no, :from =>  'AngoRussia', :text => sms_text})
              if response.ok?
 -              format.html { redirect_to @message, notice: 'A sua mensagem foi enviada.' }
 +              format.html { redirect_to messages_path, notice: 'A sua mensagem foi enviada.' }
              else
 -              format.html { redirect_to @message, alert: 'Houve um erro. Por favor tente novamente.' }
 +              format.html { redirect_to messages_path, alert: 'Houve um erro. Por favor tente novamente.' }
              end
 -           format.json { render action: 'show', status: :created, location: @message }
 -        else
 -          format.html { render action: 'new' }
 -          format.json { render json: @message.errors, status: :unprocessable_entity }
          end
        else
          format.html { redirect_to messages_path, alert: 'So pode mandar 2 mensagens a cada 24 horas.' } 

Then in layout for app/views/layouts/application.html.erb

             </fieldset>
              </div>
            </div>
 +          <div class="span3">
 +            <div class="well sidebar-nav pull-right">
 +              <div id="message_composer">
 +                <legend>Compor Mensagem</legend>
 +                <%= simple_form_for(@message) do |f| %>
 +                  <%= f.error_notification %>
 +                  <div class="form-inputs">
 +                  <%= f.input :sender_name, :label => "Seu Nome" %>
 +                    <%= f.input :recepient, :label => "Nome do Recipiente" %>
 +                    <%= f.input :phone_no, :label => "Numero Telefonico do Recipiente" %>
 +                    <%= f.input :body, :label => "Texto" %>
 +                  </div>
 +                  <div class="form-actions">
 +                    <%= f.button :submit, :value => "Enviar", :class => "btn btn-small btn-success" %>
 +                    <%= link_to 'Voltar', messages_path, :class => "btn btn-small btn-warning" %>
 +                  </div>
 +                <% end %>
 +              </div>
 +            </div><!--/.well -->
 +          </div><!--/span-->
          </div><!--/row-->
        <br />
        <br /> 

Now i am getting a Devise error:

Error

The error apeared only after i logged out. Now i can't login anymore. Please help me fix this :(

4 Answers

Hi Marcos

In your controller within the index action you're trying to use a devise method called "current_user". Since you logged out, there is no current_user!

One solution is to wrap your UI within some logic

        <% if user_signed_in? %>
          <div class="span3">
            <div class="well sidebar-nav pull-right">
              <div id="message_composer">
                <legend>Compor Mensagem</legend>
                <%= simple_form_for(@message) do |f| %>
                  <%= f.error_notification %>
                  <div class="form-inputs">
                  <%= f.input :sender_name, :label => "Seu Nome" %>
                    <%= f.input :recepient, :label => "Nome do Recipiente" %>
                    <%= f.input :phone_no, :label => "Numero Telefonico do Recipiente" %>
                    <%= f.input :body, :label => "Texto" %>
                  </div>
                  <div class="form-actions">
                    <%= f.button :submit, :value => "Enviar", :class => "btn btn-small btn-success" %>
                    <%= link_to 'Voltar', messages_path, :class => "btn btn-small btn-warning" %>
                  </div>
                <% end %>
              </div>
            </div><!--/.well -->
          </div><!--/span-->
        <% else %>
          <p>Please login to send a message!</p>
        <% end %>

Ok, but i had put in controller User == Null and made so that "if user_dont_exist" => "create_a_new_user". Isn't this a fix for that error?

So, I believe I understand what you're trying to do but it has a couple issues with it.

First, you need to refresh yourself on how classes work. Trying to check User == nil (remember null is not a concept in ruby, we use nil instead) will ALWAYS return false. When a user is logged in, they are operating as an instance of the User class, so even if someone is logged in User == nil, will still be false.

Now if I understand correctly, you're also trying to redirect the user to a different page if they aren't logged in?

Devise has a method for your controller to accomplish this goal. At the top of your controller you can wrap the method in a callback like so..

class MessagesController < ApplicationController

  before_action :authenticate_user!, only: [:index, :create]

  # ...
  # rest of the controller code omitted

end
  • just a side note, as of rails 4 they are changing the names of callbacks from "filter" to "action". So the below code above works in rails 4+. If this project you're working on is rails 3, then you need to use before_filter :authenticate_user!, only: [:index, :create]

Now, if someone tries to reach the :index or :create action of the MessagesController and they are not signed in, they will be redirected to the user_root_path (if you've created this route) or the root_path.

I highly recommend you read some of the devise documentation on their github page. It's got a lot good information!

https://github.com/plataformatec/devise

Thanks!