ActiveRecord :: StatementInvalid在AuthorsController #create中

时间:2013-09-29 05:35:05

标签: ruby-on-rails activerecord

我正在创建一个Rails博客,并使用 test samples 填充数据库,现在当我运行db:resetdb:migrate时,表格会在数据库中创建但是创建新文章或作者时显示以下错误。

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')

非常感谢帮助。

摘录来源

 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 

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

作者控制器

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

尝试使用Rails控制台创建新作者时,会弹出以下错误。

Author.new(username: 'ajay', email: 'ajkumar_25@yahoo.com', 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

3 个答案:

答案 0 :(得分:3)

schema.rb中,它表示不允许username为空:

t.string   "username",         null: false

在错误消息中,您可以看到未设置用户名,因此数据库拒绝新行。

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

您应该确保设置username

[更新]以回应原始问题中的更新:

现在你要看的关键是这一行:

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

您需要阅读attr_accessibleattr_protected。您可能需要在Author模型中使用此类内容。

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

答案 1 :(得分:0)

在尝试创建新的“作者”行时,显然缺少“用户名”字段,架构被配置为“非空”。

在某些时候,应该设置@ authors.username。这可以通过显式调用来实现 @ authors.username = params [...或批量作业。

答案 2 :(得分:0)

看起来您需要在模型上设置attr_accessible声明:

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