0

I've built a fav icon that works like a Facebook like/unlike button, and I'm trying to update it via Ajax but can't seem to get it working. I think I'm missing something simple.

events_controller.rb

def fav
  @event = Event.find(params[:id])
  current_user.toggle_flag(@event, :fav) #events_helper.rb 

  respond_to do |format|
    format.js
  end
end

events_helper.rb

def toggle_fav(event, user)
  if user_signed_in? #change icon from heart to empty heart and vice-versa
    link_to user.flagged?(event, :fav) ? #if the event is flagged
      content_tag(:span, " ", :class => "glyphicon glyphicon-heart") : #show full heart
      content_tag(:span, " ", :class => "glyphicon glyphicon-heart-empty"), #else show empty heart
      fav_event_path(event), #path that changes the state of the heart
      :remote => true
    else
      link_to content_tag(:span, " ", :class => "glyphicon glyphicon-heart-empty"), fav_event_path(event) #prompt user to sign in
  end
end

Events/index.html.erb

<% @events.each do |event| %>
  <%= render 'each_event', :event => event %>
<% end %>

_each_event.html.erb (relevant info only)

<div class="row">
  <div class="event-div">
    <div class="event-details">
      <ul><li class="fav-li"><%= render 'fav_li', :event => event %></li></ul>
    </div>
  </div>
</div>

_fav_li.html.erb

<%= toggle_fav(event, current_user) %>

fav.js.erb

$('.fav-li').html('<%=j render 'events/fav_li', :event => event, :layout => false %>');

I followed this tutorial to make the like button: http://www.youtube.com/watch?v=GG-kCSx0taU And am using the make_flaggable gem.

Right now when I update the button it directs me to http://localhost:3000/events/23/fav but that template doesn't exist (and shouldn't). The events are displayed on the event index page after going through the index filters. There are multiple events on a single page.

I'd appreciate any help! Thanks.

1 Answer 1

1

Your controller is doing format.js in the respond_to block. It's expecting a js template to exist so it can run it as the response. Something like app/views/events/fav.js.erb. This file will contain some js code that will update your view with the results of your controller action e.g. update the icon from glyphicon-heart-empty to glyphicon-heart.

Here's another question/answer discussing js.erb templates: How does js.erb work

Hope that helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.