How to force the Mercury editor to redirect to a new resource?

After viewing RailsCast # 296 about the Mercury editor , I try to redirect the editor to a newly created resource.

I can already redirect client-side using JS and window.location.href=. But for a new resource, I cannot “guess” its client-side URL. I need it to be in the server response.

However, the problem is that I do not see the possibility of using the server response in the editor. No matter what the controller displays, the server response is discarded by Mercury instead of being used as an argument to my function for mercury:saved.

Is there any way around this?

+5
source share
2 answers

I was able to do this when updating by sending a valid JSON string. I would suggest that creation works the same way. check firebug to make sure you are not getting an error in the jQuery.ajax call that Mercury uses.

posts_controller.rb

def mercury_update
  post = Post.find(params[:id])
  post.title = params[:content][:post_title][:value]
  post.body = params[:content][:post_body][:value]
  post.save!
  render text: '{"url":"'+ post_path(post.slug) +'"}'
end

mercury.js:

  jQuery(window).on('mercury:ready', function() {
    Mercury.on('saved', function() {
       window.location.href = arguments[1].url      
    });
  });

note: I use friendly_id to skip my posts.

+7
source

Server side redirection does not work, because the save button is just a call jQuery.ajax:

// page_editor.js
PageEditor.prototype.save = function(callback) {
      var data, method, options, url, _ref, _ref1,
        _this = this;
      url = (_ref = (_ref1 = this.saveUrl) != null ? _ref1 : Mercury.saveUrl) != null ? _ref : this.iframeSrc();
      data = this.serialize();
      data = {
        content: data
      };
      if (this.options.saveMethod === 'POST') {
        method = 'POST';
      } else {
        method = 'PUT';
        data['_method'] = method;
      }
      Mercury.log('saving', data);
      options = {
        headers: Mercury.ajaxHeaders(),
        type: method,
        dataType: this.options.saveDataType,
        data: data,
        success: function(response) {
          Mercury.changes = false;
          Mercury.trigger('saved', response);
          if (typeof callback === 'function') {
            return callback();
          }
        },
        error: function(response) {
          Mercury.trigger('save_failed', response);
          return Mercury.notify('Mercury was unable to save to the url: %s', url);
        }
      };
      if (this.options.saveStyle !== 'form') {
        options['data'] = jQuery.toJSON(data);
        options['contentType'] = 'application/json';
      }
      return jQuery.ajax(url, options);
    };

, success, , AJAX. . , , save.

Btw, , @corneliusk:

render { json: {url: post_path(post.slug)} }

mercury:saved.

+1

All Articles