Reputation: 2998
I am building a basic grocery list application in Rails. Each "item" has two properties: name and checked. Name is just the name of the item. Checked is supposed to indicate whether the user has "checked off" the item on their grocery list.
I put a simple method in my item controller to address this. The problem is the method will only change false to true. It will not reverse and allow me to uncheck items.
Here is the method, which is inside my item controller:
def checked
@item = Item.find(params[:id])
if [email protected]
@item.update(checked: :true)
else
@item.update(checked: :false)
end
redirect_to root_path
end
This will only work for the false to true conversation. The second half of the if statement does not appear to be working. Thoughts?
Upvotes: 1
Views: 208
Reputation: 13014
Are you sure you want to use symbols :true
and :false
there?
I would like to believe checked
to be a boolean field and boolean equivalents in Ruby are true
and false
.
Upvotes: 3
Reputation: 52396
Not sure about the underlying reason (maybe using #update
), but I'd be trying to code this more like:
def checked
@item = Item.find(params[:id])
if @item.checked
@item.update_attributes(checked: false)
else
@item.update_attributes(checked: true)
end
redirect_to root_path
end
... or ...
def checked
@item = Item.find(params[:id])
@item.update_attributes(checked: [email protected])
redirect_to root_path
end
Edit: as @MrYoshiji comments, use true
instead of :true
etc
Upvotes: 2