-
-
Save tabishiqbal/ee958452afd64d05b0de5a3259d1efb9 to your computer and use it in GitHub Desktop.
Rails Ajax Flash Messages
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div id="main" role="main"> | |
<div class="container"> | |
<div class="row"> | |
<div class="span12" id="top-div"> <!--! added "top-div" id to help with ajax --> | |
<%= render 'layouts/messages' %> | |
<%= yield %> | |
</div> | |
</div> | |
<footer> | |
</footer> | |
</div> <!--! end of .container --> | |
</div> <!--! end of #main --> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def ajax_flash(div_id) | |
response = "" | |
flash_div = "" | |
flash.each do |name, msg| | |
if msg.is_a?(String) | |
flash_div = "<div class=\"alert alert-#{name == :notice ? 'success' : 'error'} ajax_flash\"><a class=\"close\" data-dismiss=\"alert\">×</a> <div id=\"flash_#{name == :notice ? 'notice' : 'error'}\">#{h(msg)}</div> </div>" | |
end | |
end | |
response = "$('.ajax_flash').remove();$('#{div_id}').prepend('#{flash_div}');" | |
response.html_safe | |
end | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def vote | |
vote = Vote.create(voteable: @post, creator: current_user, vote: params[:vote]) | |
respond_to do |format| | |
format.html do | |
if vote.valid? | |
flash[:notice] = "Your vote was counted" | |
else | |
flash[:error] = "You can not vote on \"#{@post.title}\" more than once." | |
end | |
redirect_to :back | |
end | |
format.js do | |
if vote.valid? | |
flash.now[:notice] = "Your vote was counted" | |
else | |
flash.now[:error] = "You can't vote on that more than once" | |
end | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$("#post_<%= @post.id %>_votes").html("<%= @post.total_votes %>"); | |
<%= ajax_flash('#top-div') %> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment