Jquery 如何";“添加到收藏夹”;在rails 5中使用ajax?

Jquery 如何";“添加到收藏夹”;在rails 5中使用ajax?,jquery,ruby-on-rails,ruby,ajax,Jquery,Ruby On Rails,Ruby,Ajax,经过长时间的搜寻,我来到这里寻求帮助!如何使用rails中的ajax使收藏夹按钮正常工作 下面的代码可以工作,但当我刷新页面时,按钮返回到未链接状态(图标心空) 到目前为止,我已经使用act_as_votable gem来创建下面的内容,但现在我被卡住了 这是我的密码: 歌曲\u控制器.rb before_action :find_song, {only: [:edit, :update, :show, :destroy, :like, :unlike]} def like @song

经过长时间的搜寻,我来到这里寻求帮助!如何使用rails中的ajax使收藏夹按钮正常工作

下面的代码可以工作,但当我刷新页面时,按钮返回到未链接状态(图标心空)

到目前为止,我已经使用act_as_votable gem来创建下面的内容,但现在我被卡住了

这是我的密码:

歌曲\u控制器.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
partial\u 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_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_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' %>');

});
 resources :songs do
    member do
      get 'like', to: "songs#like"
      get 'unlike', to: "songs#unlike"
    end
  end

注:我是这方面的新手。谢谢

除非用户喜欢这首歌,否则请使用if条件:

<% 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 %> 


你成功了吗?嗨,塞巴斯蒂安,不幸的是没有成功。我已经改变了我的方法,现在使用方法创建和销毁从收藏夹控制器,而不是歌曲控制器。我稍后会发布一个问题,因为我还没有弄明白。谢谢你的邀请!