Rails controller - execute action only if the a Rails UJS method inside succeed (mutually dependent methods)

我只是一个虾纸丫 提交于 2019-12-02 09:03:53

So the transaction will only rollback if an error is thrown. If an unhandled error is thrown, your application will crash and it will show a 500 error in some way.

In order to display the response to the user, on success or error, you will need to render something. So you don't want to prevent the respond_to block from executing. One way to handle this would be to set a flag via an instance variable.

def deal_modal
  begin
    Deal.transaction do
      update_user_table
      update_userdeal_table
    end
    @success = true
  rescue
    @success = false
  end
  # show_modal_message
  respond_to do |format|
    format.js
  end  
end

Then in deal_modal.js.erb

<% if @success %>
  showModalMessage("Here is your result <variable and all>");
<% else %>
  showModalMessage("There was a problem");
<% end %>

EDIT:

Dealing with connection issues is definitely tricky and there isn't really one ideal solution. I would generally let the database continue uninterrupted and let it return either a success or failure on it's own time. For lengthy transactions, you can use a gem like delayed_job or sidekiq to process the action in the background and let the rails controller return a response saying "...pending..." or something. Unless you're using websockets on the frontend, this means continually polling the server with ajax requests to see if the background process is complete.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!