Jan
Jan

Reputation: 259

Devise current_user Form Submission "User can't be blank"

I have a simple create action in my courses_controller. I am using the current_user.built command to create the object

courses_controller.rb

class CoursesController < ApplicationController
  before_action :authenticate_user!, expect: [:index, :show] 
  before_action :set_course, only: [:show, :edit, :update, :destroy]


  # GET /courses/new
  def new
    @course = current_user.courses.build
  end





  # POST /courses
  # POST /courses.json
  def create
    @course = current_user.courses.build(course_params)
    respond_to do |format|
      if @course.save
        format.html { redirect_to @course, notice: 'Course was successfully created.' }
        format.json { render :show, status: :created, location: @course }
      else
        format.html { render :new }
        format.json { render json: @course.errors, status: :unprocessable_entity }
      end
    end
  end





  private
    # Use callbacks to share common setup or constraints between actions.
    def set_course
      @course = Course.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def course_params
      params.require(:course).permit(:name, :description, :user_id)
    end
end

When Creating a new course in the browser I get the following error:

1 error prohibited this course from being saved: User can't be blank

This is the form view:

<%= form_for(@course) do |f| %>
  <% if @course.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@course.errors.count, "error") %> prohibited this course from being saved:</h2>

      <ul>
      <% @course.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :description %><br>
    <%= f.text_area :description %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

Any ideas what could be the problem here? Devise and the current_user method are working fine in the console and on other models

Upvotes: 0

Views: 84

Answers (1)

Nicolas Blanco
Nicolas Blanco

Reputation: 11299

In your controller, the method course_params should not allow user_id to be passed in the parameters unless you want a user to create a course for another user. Because you're building the course from the current_user it's not needed.

Also check that your Course model has a validation of presence on user, not user_id.

Upvotes: 1

Related Questions