Optimistic Locking Enhancements: Gem or Core?

I’m not sure I understand what would be needed from the UJS side. If it’s in the form, UJS will simply pick it up and send it as a parameter. Are you saying it should be sent as a request header instead of a form parameter?

– Steve Schwartz

That’s right, that would not be necessary for remote: true forms. Correct me if I’m wrong but I don’t think UJS generates a form for link_to(remote: true, method: :put). It just generates an AJAX request to the server with appropriate options.

There are two ways to get this working that I know of currently:

  1. Use link_to with a url instead of a model object and stick the lock_version in as a param. link_to(@model, remote: true, method: :delete) becomes… link_to(model_path(@model, lock_version: @model.lock_version), remote: true, method: :delete) In this case the ajax request has the lock_version supplied as a query string parameter. In the case of a :post or :put it would be more appropriate to be part of the post/put data.
  2. Use link_to with data-params specified: link_to(@model, remote: true, method: :delete) becomes… link_to(@model, remote: true, method: :delete, ‘data-params’: @model.lock_version) My idea would add a simple helper option to link_to along the lines of :remote, :method, :confirm that would add the appropriate data-params for you.

link_to(@model, remote: true, method: :delete, lock_with: @model)

if link_to(:remote/:method) DID generate a form using the standard form_for under the covers then you’re right, this would be unnecessary and we could simply patch form_for/fields_for but I don’t think that’s the case with UJS as mentioned.

I thought you were talking about remote forms. Correct, UJS only creates a form for links that have data-method but are not data-remote. For remote links, it just creates an ajax request with the proper method.

So, e.g. link_to(@model, method: :delete) would turn into a form, but link_to(@model, remote: true, method: :delete) would not.

To clarify though, you’re suggesting that rails would have a :lock_with option that would translate to data-lock-with on the link and fill it with the value of @instance.lock_version, and that UJS would just need to be aware of data-lock-with and append it to the parameters?

If that’s the case, it’d be fairly easy to handle on the UJS side, so this would be more of a discussion on the side of the implementation in ActionView::Helpers::UrlHelper#link_to.

– Steve Schwartz

Sorry if I’ve been unclear. Yes, I’m suggesting a modification to link_to that would check for :lock_with options and translate that into data-params with locking_column=lock_column_value. I don’t think any change would actually be needed to jquery-ujs to support this.

To be clear, here is a gist of what I’ve monkey patched in my current application: Proposal to modify rails-core with optimistic locking enhancements or turn this into a gem. · GitHub