Stuart Pontins
Stuart Pontins

Reputation: 285

Once checkbox is true, how do you make it false once clicked again? (Rails 4)

I'm having trouble updating my boolean to be false again once clicked for a second time.

  def completed
    if @todo.update_attribute(:completed, true)
      flash[:success] = "Wowzers."
      redirect_to dashboard_path 
    else
      flash.now[:error] = "Not so wowzers..."
      render :new
    end
  end

This is what I have currently, it sets my boolean to true once clicked but I'm not sure how to if @todo.update_attribute(:completed, true, false)thinking this would be like a toggle, true then false but it's not the case.

I have also tried

  if params[:completed] == 0
    @todo.update_attribute(:completed, true)
    flash[:success] = "Wowzers."
    redirect_to dashboard_path 
  elsif params[:completed] == 1
    @todo.update_attribute(:completed, false)
    flash[:success] = "Wowzers."
    redirect_to dashboard_path 
  end

But this doesn't save to my database (true or false).

My question here is; how can I toggle my checkbox true then false, rather than just true or false?

Upvotes: 1

Views: 73

Answers (3)

Diego Polido Santana
Diego Polido Santana

Reputation: 1435

 def completed
    if  @todo.update_attribute(:completed, params[:completed])
      flash[:success] = "Wowzers."
      redirect_to dashboard_path 
    else
      flash.now[:error] = "Not so wowzers..."
      render :new
    end
  end

Upvotes: 0

Anthony E
Anthony E

Reputation: 11235

In HTML post requests, params are always passed as strings so params[:completed] == 1 will always be false. You probably want params[:completed] == '1' or params[:completed] == 'true'.

Also, if you want to toggle a param, simply use the toggle action.

@todo.toggle(:completed)

Otherwise, to save based on inequality of your param use

if @todo.update_attribute(:completed, params[:completed] != '1')
  flash[:success] = "Wowzers."
elsif 
  flash[:error] = "Couldn't update completed status"
end
redirect_to dashboard_path 

Upvotes: 2

tadman
tadman

Reputation: 211670

The basic principle of logical negation is !, the not operator, is your friend:

@todo.update_attribute(:completed, [email protected])

That will flip it back and forth.

Upvotes: 2

Related Questions