Kristiyan Tsvetanov Kristiyan Tsvetanov - 4 months ago 7
Ajax Question

Rails, js response, only a notice

In my rails app I would like to prevent users from deleting a post given some conditions. When that happens, I would like to just inform them that the post could not be deleted. The code looks like this:

def destroy
respond_to do |format|
if some_conditions
flash[:notice] = "Could not be deleted"
...
format.js {What to put here}
else
...
end
end
end


What should I put in the js response brackets so that the page is not reloaded but the notice is displayed? Thank you!

Answer

Just first, leave the format.js as it is, we will work this from the js file.

def destroy
  respond_to do |format|
    if some_conditions
      flash[:notice] = "Could not be deleted"
      format.js 
    else
    end
  end
end

Now create a file named destroy.js.erb in app/views/your controller name

in that file, destroy.js.erb

alert("Could not be deleted")

or if you want to display your notice,

take a div in your view file,

<div class="something"></div>

in your js.erb,

$('.something').text(<%= flash[:notice] %> )