ruby-on-railsruby-on-rails-3best-in-place

Rails 3 best_in_place_if how to add "id" attribute to element


I am using best_in_place_if for inline editing. Here I want to catch the id of current element edited by using the ajax success event of best_in_place.

Below is code snippet I am trying to add id attribute. But when I inspect the html, the value for id attribute is the default value generated by the bes_in_place. As per their doc, its mentioned that the default value can be changed by providing our own value.

The default value for id attribute is shown as id="best_in_place_trip_32_is_active" and I want is only id=32

best_in_place_if(current_user.admin,trip,:is_active, :type => :checkbox, :classes => 'trip_disable', :id => trip.id)

Please let me know what I am missing.


Solution

  • Firstly, you should not try to use a numeric-only ID attribute for the element, this violates the HTML specs.

    Then, to access the id of the currently edited record in the success callback, you can add the record id to the data attribute instead. Something like this should work:

    # adding the record ID to the data attribute
    best_in_place_if(current_user.admin, trip, :is_active, :as => :checkbox, :class => 'trip_disable', :data => { :id => trip.id })
    
    # accessing the record ID in the success calback
    $('.best_in_place.trip_disable').bind("ajax:success", 
                             function(){ 
                                alert('Record ID is '+$(this).data('id')); 
                             });
    

    See the Best in place docs for more info.