ajknzhol
ajknzhol

Reputation: 6450

ActiveRecord::StatementInvalid in AuthorsController#create

I am creating a Rails Blog and i populated the database with test samples and now when i run db:reset and db:migrate, tables are created in Database but shows up the following error while creating a new Article or Author.

Mysql2::Error: Field 'username' doesn't have a default value: INSERT INTO `authors` (`created_at`, `updated_at`) VALUES ('2013-09-29 05:30:43', '2013-09-29 05:30:43')

Help is appreciated.

Extracted Source

 respond_to do |format|
   **if @author.save**
     format.html { redirect_to @author, notice: 'Author was successfully created.' }
     format.json { render action: 'show', status: :created, location: @author }
   else 

Error highlights in if @author.save

Schema.rb

# encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.

ActiveRecord::Schema.define(version: 20130928053429) do

  create_table "articles", force: true do |t|
    t.string   "title"
    t.text     "body"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "image_file_name"
    t.string   "image_content_type"
    t.integer  "image_file_size"
    t.datetime "image_updated_at"
  end

  create_table "authors", force: true do |t|
    t.string   "username",         null: false
    t.string   "email"
    t.string   "crypted_password"
    t.string   "salt"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "comments", force: true do |t|
    t.string   "author_name"
    t.text     "body"
    t.integer  "article_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "comments", ["article_id"], name: "index_comments_on_article_id", using: :btree

  create_table "pages", force: true do |t|
    t.string   "title"
    t.text     "body"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "taggings", force: true do |t|
    t.integer  "tag_id"
    t.integer  "article_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "taggings", ["article_id"], name: "index_taggings_on_article_id", using: :btree
  add_index "taggings", ["tag_id"], name: "index_taggings_on_tag_id", using: :btree

  create_table "tags", force: true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

end

authors controller

class AuthorsController < ApplicationController
  before_action :set_author, only: [:show, :edit, :update, :destroy]


  def zero_authors_or_authenticated
    unless Author.count == 0 || current_user
      redirect_to root_path
      false
    end
  end

  # GET /authors
  # GET /authors.json
  def index
    @authors = Author.all
  end

  # GET /authors/1
  # GET /authors/1.json
  def show
  end

  # GET /authors/new
  def new
    @author = Author.new
  end

  # GET /authors/1/edit
  def edit
  end

  # POST /authors
  # POST /authors.json
  def create
    @author = Author.new(author_params)

    respond_to do |format|
      if @author.save
        format.html { redirect_to @author, notice: 'Author was successfully created.' }
        format.json { render action: 'show', status: :created, location: @author }
      else
        format.html { render action: 'new' }
        format.json { render json: @author.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /authors/1
  # PATCH/PUT /authors/1.json
  def update
    respond_to do |format|
      if @author.update(author_params)
        format.html { redirect_to @author, notice: 'Author was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @author.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /authors/1
  # DELETE /authors/1.json
  def destroy
    @author.destroy
    respond_to do |format|
      format.html { redirect_to authors_url }
      format.json { head :no_content }
    end
  end

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

    # Never trust parameters from the scary internet, only allow the white list through.
    def author_params
      params.require(:author).permit(:username, :email, :password, :password_confirmation)
    end
end

When trying to create a new author using Rails Console, Following error pops up.

Author.new(username: 'ajay', email: '[email protected]', password: '12345', password_confirmation: '12345').save
WARNING: Can't mass-assign protected attributes for Author: username, email, password, password_confirmation

   (0.3ms)  BEGIN
ActiveRecord::StatementInvalid: Mysql2::Error: Field 'username' doesn't have a default value: INSERT INTO `authors` (`created_at`, `updated_at`) VALUES ('2013-09-29 06:00:23', '2013-09-29 06:00:23')
    from /home/aj/.rvm/gems/ruby-2.0.0-p247/gems/activerecord-4.0.0/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:286:in `query'
  SQL (0.7ms)  INSERT INTO `authors` (`created_at`, `updated_at`) VALUES ('2013-09-29 06:00:23', '2013-09-29 06:00:23')
Mysql2::Error: Field 'username' doesn't have a default value: INSERT INTO `authors` (`created_at`, `updated_at`) VALUES ('2013-09-29 06:00:23', '2013-09-29 06:00:23')
   (0.2ms)  ROLLBACK

Upvotes: 1

Views: 2254

Answers (3)

Jeremy Green
Jeremy Green

Reputation: 8574

In your schema.rb it says that a username is not allowed to be null:

t.string   "username",         null: false

In the error message you can see that the username is not being set, so the database is rejecting the new row.

INSERT INTO `authors` (`created_at`, `updated_at`) VALUES ('2013-09-29 05:30:43', '2013-09-29 05:30:43')

You should make sure that you're setting the username.

[UPDATE] in response to an update in the original question:

Now the critical thing that you should be looking at is this line:

WARNING: Can't mass-assign protected attributes for Author: username, email, password, password_confirmation

You'll want to read up on attr_accessible and attr_protected. You probably need something like this in your Author model.

attr_accessible :username, :email, :password, :password_confirmation

Upvotes: 3

Helios de Guerra
Helios de Guerra

Reputation: 3475

Looks like you need to set your attr_accessible declaration on your model:

class Author < ApplicationController
  attr_accessible :username, :email # etc
end

Upvotes: 0

seand
seand

Reputation: 5286

When trying to create a new 'authors' row it's clearly missing the 'username' field which the schema is configured as 'not null'.

At some point @authors.username should be set. This could be via an explicit call to @authors.username = params[... or a mass assignment.

Upvotes: 0

Related Questions