空JSON可以通过模型的验证吗?

时间:2012-10-08 13:17:29

标签: ruby-on-rails ruby

在测试我的移动应用程序时,我尝试传递一个空的JSON来创建学生的记录:

  Parameters: {"student"=>{}}
WARNING: Can't verify CSRF token authenticity
   (0.1ms)  begin transaction
  SQL (0.5ms)  INSERT INTO "students" ("course_id", "created_at", "icon", "name", "password", "status", "studentID", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?)  [["course_id", nil], ["created_at", Mon, 08 Oct 2012 13:07:12 UTC +00:00], ["icon", nil], ["name", nil], ["password", nil], ["status", "pending"], ["studentID", nil], ["updated_at", Mon, 08 Oct 2012 13:07:12 UTC +00:00]]
   (3.5ms)  commit transaction
   (0.1ms)  begin transaction
  Student Exists (0.3ms)  SELECT 1 AS one FROM "students" WHERE ("students"."studentID" IS NULL AND "students"."id" != 46) LIMIT 1
   (0.1ms)  rollback transaction
Completed 422 Unprocessable Entity in 61ms (Views: 0.5ms | ActiveRecord: 5.2ms)

我的模型验证了某些字段的存在:

validates :name, :password, :status, :studentID, :presence =>true
  validate :validate_course_id
  validates :studentID, :uniqueness=>{:message=>"This studentID already exists"}

虽然JSON为空,但它会创建一条记录,几乎所有字段都为null,created_atupdated_atpending除外。

在控制器中:

  def create
    @student = Student.new(params[:student])
    # @student.update_attribute(:status,'pending')
    @student.status = 'pending'

    respond_to do |format|
      if @student.save
        upload_icon(params[:student][:icon_upload])

        format.html { redirect_to @student, notice: 'Student was successfully created.' }
        format.json { render json: @student, status: :created, location: @student }
      else
        format.html { render action: "new" }
        format.json { render json: @student.errors, status: :unprocessable_entity }
      end
    end

1 个答案:

答案 0 :(得分:1)

update_attribute

更新单个属性并保存记录,而无需通过正常的验证过程。这对现有记录上的布尔标志特别有用。当混合使用验证模块时,Base中的常规update_attribute方法将替换为此方法,默认为。

update_attributes

更新传入的Hash中的所有属性并保存记录。如果对象无效,则保存将失败并返回false。