jquery - How to "Add to favorites" with ajax in rails 5? -


after long search i've come here help! how can make favorite button ajax in rails work?

code below works, when refresh page, button unliked(icon empty heart).

so far i've used act_as_votable gem create below, i'm stuck.

here code:

songs_controller.rb

before_action :find_song, {only: [:edit, :update, :show, :destroy, :like, :unlike]}  def     @song = song.find(params[:id])     @song.liked_by current_user     respond_to |format|         format.html { redirect_to :back }         format.js { render layout: false }     end end  def unlike     @song = song.find(params[:id])     @song.unliked_by current_user     respond_to |format|         format.html { redirect_to :back }         format.js { render layout: false }     end 

partial _song.html.erb

    <div class="votes">     <% unless current_user.liked? song %>        <%= link_to unlike_song_path(song), method: :get, remote: true, class: 'unlike_song' %>         <i class="fa fa-heart-o"></i>      <% end %>        <% else %>        <%= link_to like_song_path(song), method: :get, remote: true, class: 'like_song' %>        <i class="fa fa-heart"></i>     <% end %>      <% end %>    </div>   </td> 

like.js.erb

    $('.like_song').bind('ajax:success', function(){    $(this).parent().parent().find('.vote_count').html('<%= escape_javascript @song.votes_for.size.to_s %>');    $(this).closest('.like_song').hide();    $(this).closest('.votes').html(' <%= link_to '<i class="fa fa-heart-o"></i>'.html_safe, unlike_song_path(@song), remote: true, method: :get, class: 'unlike_song' %>'); }); 

unlike.js.erb

$('.unlike_song').bind('ajax:success', function(){    $(this).parent().parent().find('.vote_count').html('<%= escape_javascript @song.votes_for.size.to_s %>');    $(this).closest('.unlike_song').hide();    $(this).closest('.votes').html('<%= link_to '<i class="fa fa-heart"></i>'.html_safe, like_song_path(@song), remote: true, method: :get, class: 'like_song' %>');  }); 

routes.rb

 resources :songs     member       'like', to: "songs#like"       'unlike', to: "songs#unlike"     end   end 

note: i'm rookie @ this. thanks!

instead checking unless if user has liked song, use if conditional:

<% if current_user.liked? song %>   <%= link_to unlike_song_path(song), method: :get, remote: true, class: 'unlike_song' %>      <i class="fa fa-heart-o"></i>   <% end %> <% else %>   <%= link_to like_song_path(song), method: :get, remote: true, class: 'like_song' %>     <i class="fa fa-heart"></i>   <% end %>   <% end %>  

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -