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

后端 未结 1 737
轮回少年
轮回少年 2021-01-29 01:47

Following another question (Rails controller - execute action only if the two methods inside succeed (mutually dependent methods)), I would like to ensure that inside one of my

相关标签:
1条回答
  • 2021-01-29 02:27

    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.

    0 讨论(0)
提交回复
热议问题