我有一个简单的表单提交。
在模型上我添加了
validates_uniqueness_of :field
但不知何故,在我的数据库中,我得到记录,其字段值为重复。
控制器方法如下
def create
field_obj=Model.find_by_field(params[:model][:field])
if field_obj.nil?
@model = Model.new(params[:model])
if (@model.save && params[:commit] == "submit")
@model.is_submitted=true
@model.submitted_timestamp=Time.now
@model.save
elsif (@model.save(:validate => false) && params[:commit] == "save")
@model.last_saved_timestamp=Time.now
@model.save
end
respond_to do |format|
if (@model.save || (@model.save(:validate => false)))
format.json { render json: @model, status: :created, location: @model }
format.js
else
format.js
format.json { render json: @model.errors, status: :unprocessable_entity }
end
end
else
@model = Model.find(field_obj.id)
if (@model.update_attributes(params[:model]) && params[:commit] == "submit")
@model.is_submitted=true
@model.save
end
respond_to do |format|
if (@model.update_attributes(params[:model])|| (@model.save(:validate => false)))
format.js
format.html { redirect_to @model, notice: 'Model was successfully updated.' }
format.json { head :no_content }
else
format.js
format.html { render action: "edit" }
format.json { render json: @model.errors, status: :unprocessable_entity }
end
end
end
end
def update
@model = Model.find(params[:id])
if (@model.update_attributes(params[:model]) && params[:commit] == "submit")
@model.is_submitted=true
@model.submitted_timestamp=Time.now
@model.save
elsif @model.update_attributes(params[:model], :validate=>false) && params[:commit] == "save"
@model.save
end
respond_to do |format|
if (@model.update_attributes(params[:model])|| (@model.save(:validate => false)))
format.js
# format.html { redirect_to @model, notice: 'Model was successfully updated.' }
format.json { head :no_content }
else
format.js
format.html { render action: "edit" }
format.json { render json: @model.errors, status: :unprocessable_entity }
end
end
end
答案 0 :(得分:0)
我认为rails 3.2 ActiveModel验证定义为
validates :field, uniqueness: true
谢谢