【问题标题】:How to "Add to favorites" with ajax in rails 5?如何在rails 5中使用ajax“添加到收藏夹”?
【发布时间】:2017-09-10 14:30:16
【问题描述】:

经过长时间的搜索,我来这里寻求帮助!如何在 Rails 中使用 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

部分 _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' %>');
});

不像.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

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

【问题讨论】:

  • 你成功了吗?
  • 嗨塞巴斯蒂安,不幸的是它没有。我现在改变了我的方法,使用来自收藏夹控制器的方法创建和销毁,而不是歌曲控制器。我稍后会发布一个问题,因为我也没有弄清楚。感谢您的提问!

标签: jquery ruby-on-rails ruby ajax


【解决方案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 %> 

【讨论】:

    猜你喜欢
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2012-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 1970-01-01
    相关资源
    最近更新 更多