1

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?

1
  • 4
    A simpler way: @item.update(checked: [email protected]?) -- Your code does not work because it is actually sending a symbol object instead of true or false, remove that semi-colon in front of true and false and it should work. Commented Aug 18, 2017 at 21:48

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.