Skip to content

Instantly share code, notes, and snippets.

@mebezac
Created February 11, 2014 21:06

Revisions

  1. mebezac created this gist Feb 11, 2014.
    12 changes: 12 additions & 0 deletions application.html.erb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,12 @@
    <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 -->
    14 changes: 14 additions & 0 deletions application_helper.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,14 @@
    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\">&#215;</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

    22 changes: 22 additions & 0 deletions posts_controller.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    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
    2 changes: 2 additions & 0 deletions vote.js.erb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,2 @@
    $("#post_<%= @post.id %>_votes").html("<%= @post.total_votes %>");
    <%= ajax_flash('#top-div') %>