1

我正在创建一个 Rails 博客,并使用和填充数据库,test samples 现在当我运行db:resetand时db: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

架构.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
4

3 回答 3

3

在你的schema.rb它说 ausername不允许为空:

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
于 2013-09-29T05:52:48.563 回答
0

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

class Author < ApplicationController
  attr_accessible :username, :email # etc
end
于 2013-09-29T06:28:38.033 回答
0

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

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

于 2013-09-29T05:51:34.150 回答