简体   繁体   English

是否将JavaScript行为添加到Ruby代码?

[英]Adding JavaScript behavior to Ruby code?

This is the controller code that I'm using for the delete action in my Rails application. 这是我在Rails应用程序中用于delete操作的控制器代码。 I'm not using a separate view for the delete action. 我没有为delete操作使用单独的视图。

def delete
    @industry = Industry.find(params[:id])
    @industry.destroy
    flash[:notice] = "Industry successfully deleted"
    redirect_to(:action => 'index')
  end

The action is triggered and executed in the index view itself, however I wish to add two things: 该动作是在索引视图本身中触发和执行的,但是我希望添加两件事:

  1. How can I create a JavaScript alert that warns the user before deleting the object? 如何创建JavaScript警报,以在删除对象之前警告用户?
  2. The flash message stays at the top of the index page. 即兴消息停留在索引页面的顶部。 How can I add JavaScript so that the flash message box appears and vanishes after 10 seconds? 如何添加JavaScript,以使Flash消息框出现并在10秒后消失?

Basically, how do I intercept the destroy action in Rails 4? 基本上,我该如何拦截Rails 4中的destroy动作?

To remove the flash after 10 seconds: 要在10秒钟后移除闪光灯,请执行以下操作:

$('.your-alert-div').delay(10000).fadeOut(400); // The fadeOut is just a transition I added. you can do remove() instead

Similarly, you can use setTimeout. 同样,您可以使用setTimeout。

window.setTimeout(function() {
  $(".alert").fadeTo(500, 0).slideUp(500, function(){
      $(this).remove();
  });
}, 6000);

To ask a user through a JavaScript alert, before they delete something, you can do something like this to your link: 要通过JavaScript警报询问用户,在用户删除某些内容之前,您可以对链接执行以下操作:

<%= link_to "Delete", object, :method => :delete, :data => { :confirm => "Are you sure?" } %>

The alert has nothing to do with this action. alert与此操作无关。 You need to render that JavaScript in the previous page, the one that makes a request to this action. 您需要在上一页中渲染该JavaScript,该页面对此动作进行了请求。

By the time the action is invoked, it's too late to prompt the user. 到操作被调用时,提示用户为时已晚。

The notice is similarly unrelated to this action. 通知与此与此无关。 You need some JavaScript which is attached to your layout, which uses setTimeout to hide the notice element when its present in the DOM. 您需要一些附加到布局的JavaScript,该布局使用setTimeout来隐藏当通知元素出现在DOM中时使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM