[英]boolean field not updating in Rails
我正在構建一個基本的 crud 應用程序; 使用我的 controller 更新task
的方法如下:-
def update
@task = Task.find(params[:id])
respond_to do |format|
if @task.update(task_params)
format.html { redirect_to task_url(@task), notice: "Task was successfully updated." }
format.json { render :show, status: :ok, location: @task }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: @task.errors, status: :unprocessable_entity }
end
end
end
Tasks
有一個 boolean 字段completed
。
create_table "tasks", force: :cascade do |t|
t.string "title"
t.text "content"
t.string "createdby"
t.datetime "createdat", precision: 6
t.boolean "completed"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
問題是當我嘗試更新任務時,除了completed
之外的所有字段都會更新。 更新completed
為假給我Task updated message
成功,但 boolean 字段的值恢復為true
無論我更改多少次。
PS 我正在作為參數傳遞completed
的字段。
下面是渲染completed
boolean 字段的復選框的視圖:-
<div class="form field-group">
<%= form.check_box :completed, { class: "class-name", style: "style"}, "checked-value", "unchecked-value" %> Completed
</div>
我是 ROR 的新手,我們將不勝感激。
嘗試從控制台更新任務如下:-
=> Task.last.update(:completed => false).save
確實更新,但每次從瀏覽器 ui 完成更新時都會恢復為true
您的復選框值似乎是"checked-value", "unchecked-value"
所以當它被選中時它返回一個字符串"checked-value"
或"unchecked-value"
因為它們都是字符串,所以它們評估為true
. 將它們更改為true
和false
。
<%= form.check_box :completed, { class: "class-name", style: "style"}, "true", "false" %> Completed
<%= form.check_box :completed, { class: "class-name", style: "style"}, "checked-value", "unchecked-value" %>
如果未勾選該復選框,您的服務器將收到"unchecked-value"
作為已完成的值。 這仍然會評估為真。 您可以通過在控制台中執行以下操作來嘗試此操作:
> task = Task.new
> task.completed = "unchecked-value"
> puts task.completed
true
默認未選中的值為“0”,這將給出預期的行為。
> task.completed = "0"
> puts task.completed
false
除非您有理由使用“未經檢查的值”,否則修復只是使用默認值:
<%= form.check_box :completed, { class: "class-name", style: "style"} %>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.