I am building a basic crud app; with my controller method for updating a task
as follows :-
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
have a boolean field 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
Issue is when I am trying to update tasks, all fields apart from completed
gets updated.
Updating completed
to false gives me Task updated message
successfully, but value of the boolean field reverts back to true
no matter how many times I change it.
P.S. I am passing in field completed
as params.
Below is the view for rendering the checkbox for boolean field completed
:-
<div >
<%= form.check_box :completed, { class: "class-name", style: "style"}, "checked-value", "unchecked-value" %> Completed
</div>
I am totally new to ROR & any help would be appreciated.
Tried updating task from console as follows :-
=> Task.last.update(:completed => false).save
Does update, but reverts back to true
everytime update is done from browser ui
CodePudding user response:
Your values for the checkbox appear to be "checked-value", "unchecked-value"
so when it is checked it returns a string of either "checked-value"
or "unchecked-value"
Since they are both strings they evaluate to true
. Change them to true
and false
.
<%= form.check_box :completed, { class: "class-name", style: "style"}, "true", "false" %> Completed
CodePudding user response:
<%= form.check_box :completed, { class: "class-name", style: "style"}, "checked-value", "unchecked-value" %>
When the check box is not ticked your server will receive "unchecked-value"
as the value for completed. This will still evaluate to true. You can try this by doing the following in the console:
> task = Task.new
> task.completed = "unchecked-value"
> puts task.completed
true
The default unchecked value is "0" which will give the expected behaviour.
> task.completed = "0"
> puts task.completed
false
Unless you have a reason for having "unchecked-value" a fix would be just to use the defaults:
<%= form.check_box :completed, { class: "class-name", style: "style"} %>