通过 Rails 中的 simple_form_for 传递数据时获取 NotNullViolation

Getting NotNullViolation when passing Data through simple_form_for in Rails

通过 simple_form_for 传递数据时出现上述错误。我的视图、控制器和数据库文件包含在下面。这看起来我没有在控制器中获得 simple_form_for 提交的值。请注意,在我的数据库 table 中,属性 statusnot null 并且我没有将其作为视图的输入。我该如何解决这个错误?

数据库

create_table "users", force: :cascade do |t|
t.integer "team_lead_id"
t.string "name", null: false
t.string "email", null: false
t.string "password", null: false
t.date "joining_date", null: false
t.integer "status", null: false
t.integer "role"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end

查看

<%= simple_form_for @user , :url => user_createUser_url, :method => :post do |f| %>
    <%= f.input :name %><br />
    <%= f.input :email%><br />
    <%= f.input :password %><br />
    <%= f.input :joining_date, as: :date, order: [:day, :month, :year] %><br/>
    <%= f.submit "Create User" %>
  <% end %>

控制器

def createUser

    fresh = User.new

    fresh.name = params[:name]
    fresh.email = params[:email]
    fresh.password = params[:password]
    fresh.joining_date = params[:joining_date]
    fresh.status = 1
    fresh.role = 3

    if fresh.save
      flash[:notice] = "User Created"
      redirect_to(:action => index)
    else
      flash[:notice] = "Creating failed"
      redirect_to(:action => index)
    end

  end

我遇到了这个错误

PG::NotNullViolation: ERROR: null value in column "name" violates not-null constraint DETAIL: Failing row contains (12, null, null, null, null, null, 1, 3, 2018-11-12 13:37:54.589835, 2018-11-12 13:37:54.589835). : INSERT INTO "users" ("status", "role", "created_at", "updated_at") VALUES (, , , ) RETURNING "id"

createUser 不是 CRUD 约定,而是使用 create 但你也应该使用 strong parameters 并且也不要使用像 fresh 这样愚蠢的名称而是模型对象应按语义命名。

def create
  user = User.new(permitted_params)
  user.status = 1
  user.role = 3

  if user.save
    flash[:notice] = "User Created"
      redirect_to(:action => index)
  else
    flash[:notice] = "Creating failed"
    redirect_to(:action => index)
  end
end

def permitted_params
  params.require(:user).permit(:name, :email, :password, :joining_date)
end

您可能不需要 joining_date,因为您有 created_at,但如果您确实想保留该字段,至少使用名称 joined_datejoin_date因为它永远是过去时。事实上,用户永远不会 "joining",他们要么有,要么还没有 "joined"。

作为旁注,您永远不应该以未加密的方式存储密码,也许请参阅 bcrypt