I have a model called Question, and it has action create;
My goal is to display a flash message instantly, using a helper method (show_alert
for example) when the instance is not valid.
question_controller.rb
def create
question = Question.new(question_params)
if question.save then
redirect_to show_question_path(question.id)
else
show_alert(:warning, question.errors)
end
end
application_controller.rb
helper_method :show_alert
def show_alert(type, message)
@type = type; @msg = message
respond_to do |format|
format.js { render :template => 'alert.js.erb'}
end
end
alert.js.erb
var div = $('<div></div>').addClass(`alert alert-${@type}`)
$('<ul></ul>').append( $('<li></li>').html(@msg)
div.append(ul)
$('#alerts').html(div)
But instead of displaying the flash, I get only the partial's code on the white screen.
Since I've used respond_to I got another error: ActionController::UnknownFormat
I need the snippet of code in alert.js.erb
to be executed, in order to render the flash, I think the trick is somewhere in the render
function, but two hours of googling were just a waste of time.
Please help! Thank you in advance