cbmeeks
cbmeeks

Reputation: 11420

How can I toggle a boolean field in Rails 3 using AJAX?

I have a column in a table called Complete that is a boolean.

How can I (using the Rails 3 / JQuery way) provide a link that will toggle that via AJAX?

Historically, I've simply created my own jquery file, grabbed the click event, and done it by hand. But it really seems like I'm missing something by not doing it the "rails" way. If that makes sense.

I guess I still don't understand how the responds_to JS works, JS with ERB, etc.

Is there a good, up-to-date tutorial on how to do this?

Thanks.

Upvotes: 1

Views: 1299

Answers (1)

radosch
radosch

Reputation: 619

see this post, Rails 3, Custom Actions, and HTML request methods

and use UJS on top of it.

so you have a fallback, if javascript is disabled

a possible method in the controller looks like that:

  # GET /surveys/1/close
  def close
    @survey.close!
    flash[:success] = "Survey successfully closed!"
    respond_to do |format|
      format.html { redirect_to(surveys_url) }
      format.xml  { head :ok }
      format.js { render :partial => 'list_item', :locals => { :survey => @survey } }
    end
  end

you could also use a state machine to change the state of your object.

Upvotes: 2

Related Questions