ben
ben

Reputation: 21

Ruby on Rails Devise cant obtain current_user_id

I generated a Request Model thats traits include a Address and a body. The request belongs to a user. When I attempt to set the request user_id to current_user.id I get "undefined method `id' for nil:NilClass" when I am logged in as a user.

Request controller:

    class RequestsController < ApplicationController
      def new
        @request = Request.new

      end

      def show
        @request = Request.find(params[:id])
      end

      def create
        @request = Request.new(request_params)
        @request.user_id = @current_user.id
        if @request.save
          flash[:notice] = "Successfully created request!"
          redirect_to request_path(@request)
        else
          flash[:alert] = "Not Saved"
          render :new
        end
      end


  private
  def request_params
    params.require(:request).permit(:address, :body)
  end
end

New request HTML:

<div class= "center">
  <h1> Create a Request</h1>
</div>

<div class= "row">
  <div class="col-md-6 col-md-offset-3">
    <%= form_for @request do |f| %>

    <div class="form-group">
      <%= f.label :address %>
      <%= f.text_field :address%>
    </div>

    <div class="form-group">
      <%= f.label :body %>
      <%= f.text_area :body %>
    </div>

    <div class= "center"><%= f.submit "Submit", class: 'btn btn-primary' %></div>
    <% end %>
  </div>
</div>

Upvotes: 0

Views: 325

Answers (1)

Rockwell Rice
Rockwell Rice

Reputation: 3002

You should change this line

@request.user_id = @current_user.id

To this

@request.user_id = current_user.id

The @ symbol is used to create instance variables. With Devise current user is not an instance variable but a method so you cannot access it that way. If you have not read over it yet, you can get a whole list of useful methods here : https://github.com/plataformatec/devise. Keep in mind you use it exactly how they have it written. So, for example, user_signed_in? is not @user_singed_in? or anything like that.

Upvotes: 4

Related Questions