经过长时间的搜索,我来这里寻求帮助!如何在轨道中使用ajax制作收藏夹按钮?
下面的代码有效,但是当我刷新页面时,按钮又回到不受欢迎的状态(带有空心的图标)。
到目前为止,我已经使用了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
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' 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 :(得分:1)
相反,除非用户喜欢这首歌,否则请使用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 %>