RegistrationReConord中的ActiveRecord :: StatementInvalid #create

时间:2016-02-28 10:16:37

标签: ruby-on-rails ruby postgresql activerecord devise

我一直坚持这个例外。我使用的是rails 4.2.5.1和ruby 2.3.0。我正在使用rails中的设计创建一个模型。我已经覆盖了设计创建方法。我在postgres中收到错误PG :: NotNullViolation:ERROR:列“id”中的空值违反了非空约束。我希望在我传递的参数的帮助下创建ID。 ID未创建。由于我是铁杆新手,现在已经被困了好几个小时了。

请求 参数:

{"utf8"=>"✓",
 "authenticity_token"=>"SAiVJEULEa7RsieW+OTW1a/946f2xVbhA/sZWWn3KdX1Wt0Ozx+tq6eQfhTpaAJ+4Cxu2DMnPfqd0Vcle7ow0w==",
 "employee"=>{"email"=>"safi123@gmail.com",
 "first_name"=>"sss",
 "last_name"=>"dddnjnfj",
 "phone_number"=>"9944253677",
 "alternative_phone_number"=>"9659392682",
 "alternative_email_id"=>"dd@gmail.com",
 "date_of_joining"=>"12-02-2015",
 "date_of_birth"=>"03-02-1999",
 "status"=>"Active",
 "gender"=>"M",
 "blood_group"=>"A +"},
 "commit"=>"Sign up"}

应用程序控制器:

class ApplicationController < ActionController::Base

  protect_from_forgery with: :exception
  before_action :authenticate_employee!


before_filter :configure_permitted_parameters, if: :devise_controller?

  protected

    def configure_permitted_parameters
      devise_parameter_sanitizer.for(:sign_up) do |employee_params|
        employee_params.permit  :first_name, :last_name, :blood_group, :phone_number, :gender, :date_of_birth, :email, :alternative_email_id, :status, :date_of_joining, :alternative_phone_number
      end
      devise_parameter_sanitizer.for(:account_update) do |employee_params|
        employee_params.permit :first_name, :last_name, :blood_group, :phone_number, :gender, :date_of_birth, :email, :alternative_email_id, :status, :date_of_joining, :alternative_phone_number
      end
    end

end

注册控制器

class RegistrationsController < Devise::RegistrationsController
  def new
    super
  end
  def index
    @employees = Employee.all
  end
 def create
  @employee = Employee.new(employee_params)
    if @employee.save
      redirect_to :action => :new
    else
      render 'new'
    end
    @employee.save  
  end
    # Never trust parameters from the scary internet, only allow the white list through.
    def employee_params
      params.require(:employee).permit(:first_name, :last_name, :blood_group, :phone_number, :gender, :date_of_birth, :email, :alternative_email_id, :status, :date_of_joining, :alternative_phone_number)
    end

  def update
    super
  end
end

数据库架构:

我可以理解ID没有生成,也没有存储在数据库中。这里有什么问题?任何人都可以解释我的错误是什么? enter image description here

1 个答案:

答案 0 :(得分:0)

您要将员工记录保存两次。这可能是问题,请只保存一次。我已经给出了行动,请检查。

def create
  @employee = Employee.new(employee_params)
    if @employee.save
      redirect_to :action => :new
    else
      render 'new'
    end
   /* Here you had saved again. */
  end

您的员工参与,

def employee_params
    params.require(:employee).permit(:first_name, :last_name, :blood_group, :phone_number, :gender, :date_of_birth, :email, :alternative_email_id, :status, :date_of_joining, :alternative_phone_number)
end

现在你将通过params获取id,它将被保存。