rcrusoe
rcrusoe

Reputation: 451

Using Ajax to load a rails partial

I've read through a ton of tutorials, and I can't seem to get this to work. I am using the acts_as_votable gem and am attempting to load the 'unlike' partial when someone 'likes' a resource (my votable model).

Resources Index:

<div class="votes">
    <% if (current_user.liked? resource) %>
        <!-- Unlike -->
        <%= render(:partial => 'unlike', :locals => {:resource => resource})%>
    <% else %>
        <!-- Like -->
        <%= render(:partial => 'like', :locals => {:resource => resource})%>
    <% end %>
</div>

Resources Controller:

def index
  @resources = Resource.all.order(:cached_votes_up => :desc)
end

def like
  @resource = Resource.find(params[:id])
  @resource.liked_by current_user
  respond_to do |format
    format.html { redirect_to :back }
    format.js { render layout: false }
  end
end

Routes

Rails.application.routes.draw do
  resources :resources do 
    member do
      get "like", to: "resources#like"
      get "unlike", to: "resources#unlike"
    end
  end
end

like.js.erb

$('.like_resource').bind('ajax:success', function(){
   $(this).closest('.like_resource').hide();
   $(this).closest('.votes').html('<%= escape_javascript (render partial: 'like', locals: { :resource => resource } ) %>');
});

_like.html.erb

<%= link_to like_resource_path(resource), method: :get, remote: true, class: 'like_resource' do %>
    <button class="ui basic compact icon right floated button vote_count">
        <i class="heart icon" style="color: #F1F1F1"></i> <%= resource.get_likes.size %>
    </button> 
<% end %>

Current Functionality - When I click on the like button, the like is registered, but the ajax does not load the partial. I need to reload the page to see the updated unlike button.

If I change the like.js.erb file to include a simple link instead of loading a partial, it seems to load correctly.

$('.like_resource').bind('ajax:success', function(){
   $(this).closest('.like_resource').hide();
   $(this).closest('.votes').html(' <%= link_to "Unlike", unlike_resource_path(@resource), remote: true, method: :get, class: 'unlike_resource' %>');
});

Upvotes: 0

Views: 787

Answers (1)

rcrusoe
rcrusoe

Reputation: 451

Got this fixed! The console was posting a 500 internal error, but provided little insight into what was happening. I hopped into log/development.log and found this error:

undefined local variable or method `resource'

I was missing an "@" in the ajax partial local variable call. Change the final line to this:

$(this).closest('.votes').html('<%= escape_javascript (render partial: 'like', locals: { :resource => @resource } ) %>');

Upvotes: 1

Related Questions