2012-10-08 63 views
0

在測試我的移動應用程序,我想傳遞一個空的JSON打造學生的記錄:空的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是空的,它將創建幾乎所有字段都爲空的記錄,除了created_at,updated_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

對於update_attribute

更新單個屬性並保存記錄,而不通過正常驗證過程打算。這對於現有記錄上的布爾標誌特別有用。默認情況下,混合驗證模塊時,Base中的常規update_attribute方法將替換爲此方法。

對於update_attributes

更新所有從屬性傳入的散列並保存記錄。如果該對象無效,則保存將失敗並返回false。

+0

感謝您的回答以及編輯我的問題陳述的人:) 我真的很感謝您能理解我的回覆。我昨天很想回復。我也發佈了控制器中的創建方法:) – code4j

+0

酷:)沒問題。 –

相關問題