开发者

Rails3 responding with js after json update

开发者 https://www.devze.com 2023-02-25 05:20 出处:网络
开发者_开发知识库using http://blog.bernatfarrero.com/in-place-editing-with-javascript-jquery-and-rails-3/
开发者_开发知识库

using http://blog.bernatfarrero.com/in-place-editing-with-javascript-jquery-and-rails-3/

The gem uses json to update, but how can I trigger my update.js.erb to update the different parts of my pages?

EDIT Using this in an invoice page. every item in the invoice has a price field that can be updated with best_in_place.

I need to update the Total Price for line item and amount due for invoice only after field has been updated successfully.

Ended up with something like:

 respond_to do |format|
        if @item.update_attributes(params[:item])
          format.html { redirect_to order_url(@item.order_id), :notice => "Successfully updated item." }
          format.js {  }
          format.json { head :ok } 

Edited best_in_place.js line #175

loadSuccessCallback : function(data) {
    this.element.html(data[this.objectName]);
        // Binding back after being clicked
    $(this.activator).bind('click', {editor: this}, this.clickHandler);
    if(this.objectName == "item") $.getScript('update.js'); // If its an item, call update.js.erb 
  },


I wanted to do the exact same thing with best_in_place pcasa. In the current version (1.0.2), the loadSuccessCallback function triggers an ajax:success event. That allows you to do this in your application.js:

$('.best_in_place')
    .best_in_place()
    .bind('ajax:success', function(e) {
        // do your post-json call magic
    });


You don't need a view update.js.erb. As ezkl already pointed out, you need to set the respond_to of your controller to json. In addition, you need to activate best-in-place in your public/javascripts/application.js

$(document).ready(function() {
  jQuery(".best_in_place").best_in_place()
});

and add it in your view:

 <td><%= best_in_place task, :name, :type => :input, :nil => "Click to edit" %></td>

I have a tutorial on Ajax with Prototype and JQuery on my own site - and the JQuery Part uses best-in-place: http://www.communityguides.eu/articles/15


Have you tried something along the lines of:

def update
  @user = User.find(params[:id])

  respond_to do |format|
    if @user.update_attributes(params[:user])
      format.html { redirect_to(@user, :notice => 'User was successfully updated.') }
      format.json { head :ok }
      format.js
    else
      format.html { render :action => "edit" }
      format.json  { render :json => @user.errors, :status => :unprocessable_entity }
    end
  end
end

I haven't tested this with the code in the tutorial, but the idea is that you have to tell the controller method to load the Javascript file. I'm not sure how this will interact with the redirect, but the principle is correct.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号