Hi I have a status controller where I render js
template when a user deletes a status. This is the controller code:
def destroy
@status = Status.where(id: params[:id]).first
if @status.present?
make_subject(@status, Constants::Subject::BREAK)
respond_to do |format|
format.html { redirect_to root_path, notice: 'deleted' }
format.json { head :no_content }
format.js { render layout: false }
end
end
end
In my destroy.js.erb
, I have:
$("#clear_status_<%= @status.id %>").fadeOut();
I have a partial which renders flash messages
<div id = "notice_wrapper">
<% if alert %>
<div class = "alerty">
<p> <%= alert %> </p>
</div>
<% elsif notice %>
<div class = "notice">
<p> <%= notice %> </p>
</div>
<% end %>
</div>
Once the status gets deleted successfully I want a notice which informs the user that the status is deleted successfully I want to display that message by rendering this partial. How can I achieve this?
You will need a way to tell in your response if the delete was successful. And if it was, then show your notice.
For this purpose, I'll create a @deleted
variable which will be boolean, and will be set to true if delete is successful, otherwise, false.
Following is the controller code:
def destroy
@status = Status.find(params[:id])
@deleted = false
if @status.destroy
@deleted = true
end
respond_to do |format|
format.html
format.json
format.js
end
end
and the destroy.js.erb
file, you will have something of this sort:
<% if @deleted %>
$(".notice").html(<%= render 'notice_partial' %>)
<%= escape_javascript(alert("deleted successfully")) %>
<% end %>
$("#clear_status_<%= @status.id %>").fadeOut();
You can do it with JQuery. If put your own element instead of 'nav'
where u want to show notice.
$('nav').after("<div class='alert alert-success'> Successfully Destroyed </div>");
$("#clear_status_<%= @status.id %>").fadeOut.fadeOut(250, function(){
$(this).remove();
});
Also Update your destroy method.
def destroy
@status = Status.find_by(id: params[:id])
if @status.present?
make_subject(@status, Constants::Subject::BREAK)
respond_to do |format|
#format.html { redirect_to root_path, notice: 'deleted' } # yr calling it async to destroy. format.html is needless.
format.json { head :no_content }
format.js
end
end
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.