如何在Rails中使Ajax与form_tag一起使用?

时间:2019-03-30 03:31:41

标签: ruby-on-rails ruby ajax

我尝试了多个Youtube教程和StackOverflow问题,但我的Ajax仍然无法与form_tag一起使用。我该如何运作?

基本上,我希望在选中复选框并单击提交按钮后删除课程的td。

代码如下:

_courses.html.erb:

<%= form_tag delete_drafts_path, remote: true do %>

  <%= submit_tag 'Update', class: 'course-container-new-row-button' %>

  <% @courses_drafts.each do |course| %>
   <tr>
    <td">
     <div class="check-button">
      <label>
       <%= check_box_tag "approved_ids[]", course.id, nil %>
        <span>
         <i class="fa fa-check" aria-hidden="true"></I>
        </span>
       </label>
      </div>
     </td>
    </tr>
  <% end %>
<% end %>

courses.js.erb:

$('.course-container-new-row-button').bind("ajax:success", function() {
    $(this).closest('td').fadeOut();
})

courses_controller.rb:

def courses 
  @courses_pending = Course.where(activity: 2).page(params[:page]).order('day ASC')

  respond_to do |format|
    format.js
    format.html
  end
end

路线:

  post :delete_drafts, to: "courses#courses", as: :delete_drafts

1 个答案:

答案 0 :(得分:0)

要使远程表单正常工作,您必须在rails-ujs中包含jquery-ujs(对于Rails <5.1则为application.js),请检查其是否包含以下行:

//= require rails-ujs