This is the controller code that I'm using for the delete action in my Rails application. I'm not using a separate view for the delete action.
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:
- How can I create a JavaScript alert that warns the user before deleting the object?
- 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?
Basically, how do I intercept the destroy action in Rails 4?
2 Answers 2
To remove the flash after 10 seconds:
$('.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.
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:
<%= link_to "Delete", object, :method => :delete, :data => { :confirm => "Are you sure?" } %>
8 Comments
data-confirm message.@industry or industryThe alert has nothing to do with this action. You need to render that JavaScript in the previous page, the one that makes a request to this action.
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.
Basically how do I intercept the destroy action in Rails 4.has nothing to do with the rest of your question. You're not "intercepting the destroy action in rails", you are asking the user if they want to click that link. When they click it, it sends a request to your server, which then makes the rails destroy action happen.