RESTful in-place edit in Rails and jRails/jQuery

I’ve been using jRails in my recent Rails projects, the original Rails in-place editing plugin uses script.aculo.us, there is a jRails version of it, but neither of them is RESTful – they both create extra actions to update the in-place edit fields.

I found janv’s rest_in_place plugin and it uses the default update action to update the field, so no routes modifications are necessary. I had some problems with the plugin at first but after a pull-request correspondence the plugin now works well. Here are the highlights on how to use it, keep in mind that I use HAML.

The plugin’s init.rb doesn’t load anything for you, so you have to go into your application layout and include the js file:

    = javascript_include_tag 'jquery.rest_in_place.js'

If you have CSRF protection on, this plugin also requires you to set a javascript var. If you have jRails it automatically append the token in ajax requests, but then you would have to modify the plugin a bit to get it to work.

:javascript
  rails_authenticity_token = '#{form_authenticity_token}'

In your controller’s show action, handle the javascript response:

  def show
    respond_to do |format|
      format.html # show.html.erb
      format.js   { render :json => @model }
    end
  end

then you can render the helper in the views:

- div_for @model do
  %p
    = label_tag "Name"
    %br
    %span.rest_in_place{ :attribute =>'name' }
      =h @model.name
  %p
    = label_tag "Location"
    %br
    %span.rest_in_place{ :attribute => 'location' }
      =h @model.location

, , , , , , ,

3 Responses to RESTful in-place edit in Rails and jRails/jQuery

  1. Tiff December 6, 2008 at 7:31 pm #

    Hi Andrew,

    Question…did you terminate your Verizon contract before you got your iphone? Did you have to pay the early termination fee?

    Thanks,
    Tiff

  2. Chuck Bergeron May 8, 2009 at 1:27 pm #

    Super rad, thanks for this! Now to figure out how to handle acts_as_taggable_on and TinyMCE content…

  3. monde November 7, 2009 at 10:00 pm #

    Awesome in place editing tips for jQuery + HAML, you saved me a ton of time.

    the raw HAML for the setting the authenticity token up is this

    %script{:type => "text/javascript"}
    = "rails_authenticity_token = '#{form_authenticity_token}';"

    corresponding to
    <script type="text/javascript">
    rails_authenticity_token = '<%= form_authenticity_token %>'
    </script>

Leave a Reply