Twitter Bootstrap Rails button dropdown no responding to AJAX

后端 未结 2 1690
陌清茗
陌清茗 2020-12-19 23:36

I have a Rails 4 app that is using Bootstrap. I am creating a dashboard page that shows buttons that are color coded to represent the status of the tool it represents. The H

2条回答
  •  星月不相逢
    2020-12-20 00:10

    So I finally figured this one out. The key was having the workflow down: :remote => true connects to the toggle_in_service method in the controller that then calls the toggle_in_service.js.erb file which finally calls toggle_button.html.erb. I also found that when working in Bootstrap it's probably best to try and target an existing

    for replacement rather than wrap a piece of bootstrap code in another div. Not sure on that but it seemed to matter. Here is the code that worked:

    dashboard.html.erb view snippet:

     <% status_link = tool.in_service ? "Put Out of Service" : "Put In Service" %>
     <% button_link = "#{tool.location}-#{tool.name.singularize}"+'
    '+" #{tool.serial}" %>
    <%= raw(button_link) %>

    This creates a Bootstrap dropdown menu attached to a button that is color coded by the status of the tool.

    The first link in the dropdown menu is a remote ajax call to the toggle_in_service controller, passing the tool.id paramter. The controller method looks like:

    def toggle_in_service
       status_change = @tool.in_service ? false : true
       @tool.update(:in_service => status_change)
       respond_to do |format|
         format.html { redirect_to(@tool) }
         format.js
      end
    end
    

    The boolean value for tool.in_service gets flipped and then calls toggle_in_service.js.erb:

    <% btn_id = "btn#{@tool.id}" %>
    
    $('#<%=btn_id%>').html('<%= escape_javascript(render :partial => "toggle_button") %>');
    

    Which does an AJAX render of the _toggle_button.html.erb partial:

    <% button_link = "#{@tool.location}-#{@tool.name.singularize}"+'
    '+" #{@tool.serial}" %> <% status_link = @tool.in_service ? "Put Out of Service" : "Put In Service" %> <%= raw(button_link) %>

    Works great! The entire div for the dropdown and the button get updated by AJAX. I'm posting this in case someone looks for something similar. I search many hours on the web and on Stack Overflow, but never found what I needed. I did some reading up on Rails AJAX to figure out what I was doing wrong.

提交回复
热议问题