2017-09-10 59 views
1

經過漫長的搜索,我來到這裏尋求幫助!如何使用ajax在軌道上工作最喜歡的按鈕?如何使用ajax在rails 5中「添加到收藏夾」?

下面的代碼工作,但是當我刷新頁面時,按鈕返回到unliked(空心圖標)。

到目前爲止,我已經使用了act_as_votable gem來創建下面這個,但現在我被卡住了。

這裏是我的代碼:

songs_controller.rb

before_action :find_song, {only: [:edit, :update, :show, :destroy, :like, :unlike]} 

def like 
    @song = Song.find(params[:id]) 
    @song.liked_by current_user 
    respond_to do |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 do |format| 
     format.html { redirect_to :back } 
     format.js { render layout: false } 
    end 

部分_song.html.erb

<div class="votes"> 
    <% unless current_user.liked? song %> 
     <%= link_to unlike_song_path(song), method: :get, remote: true, class: 'unlike_song' do %> 
     <i class="fa fa-heart-o"></i> 
    <% end %> 
     <% else %> 
     <%= link_to like_song_path(song), method: :get, remote: true, class: 'like_song' do %> 
     <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 do 
    member do 
     get 'like', to: "songs#like" 
     get 'unlike', to: "songs#unlike" 
    end 
    end 

注:我在這個新秀。謝謝!

+0

你做工作? –

+0

嗨塞巴斯蒂安,不幸的是沒有。現在我改變了我的方法,使用方法創建和銷燬收藏夾控制器,而不是歌曲控制器。我稍後會發佈一個問題,因爲我還沒有想到。感謝問! – Kurta

回答

1

除了用,除非用戶是否喜歡這首歌,使用的檢查,如果條件:

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