当我点击不喜欢按钮时,如何使类似的计数器停止运行,反之亦然?

时间:2015-08-05 13:19:31

标签: ruby-on-rails voting vote vote-up-buttons

这是具有类似操作的控制器:

 def like
like = Like.create(like: params[:like], user: current_user, story: @story)

respond_to do|format|
  if like.valid?
    format.js
  else
    format.js {render status: 403, js: "alert('You can only like/dislike a story once')"}
  end
end

这是具有模型计数器的模型:

   def thumbs_up_total
       self.likes.where(like: true).size
   end

   def thumbs_down_total
       self.likes.where(like: false).size
   end

这是视图。我从模型中得到了反击。 '竖起大拇指'并且'拇指向下':

          <div class="pull-right">
              <%= link_to like_story_path(story, like: true), method: :post, data: { remote: true } do %>
              <div class="likes"></div>
              <% end %>
              <div id = "like-<%= story.id %>">
              <%= story.thumbs_up_total %>
              </div>
              <%= link_to like_story_path(story, like: false), method: :post, data: { remote: true } do %>
              <div class="dislikes"></div>
              <% end %>
              <div id="dislike-<%= story.id %>">
              <%= story.thumbs_down_total %>
              </div>
           </div>

2 个答案:

答案 0 :(得分:0)

我猜你是在问这样的事,对吗?

<div class="pull-right">
              <%= link_to like_story_path(story, like: true), method: :post, data: { remote: true } do %>
              <div class="likes"></div>
              <% end %>
              <div id = "like-<%= story.id %>">
              <%= story.thumbs_up_total - story.thumbs_down_total%>
              </div>
              <%= link_to like_story_path(story, like: false), method: :post, data: { remote: true } do %>
              <div class="dislikes"></div>
              <% end %>
              <div id="dislike-<%= story.id %>">
              <%= story.thumbs_down_total - story.thumbs_up_total %>
              </div>
           </div>

答案 1 :(得分:0)

将视图的部分移动到局部视图,创建like.js并用代码填充它以渲染部分视图。

首先将您的观看代码更改为此

      <div class="pull-right">
          <%= link_to like_story_path(story, like: true), method: :post, data: { remote: true } do %>
          <div class="likes"></div>
          <% end %>
          <%= render "thumbs_up" %>
          <%= link_to like_story_path(story, like: false), method: :post, data: { remote: true } do %>
          <div class="dislikes"></div>
          <% end %>
          <%= render "thumbs_down" %>>
       </div>

然后创建两个新的部分。

# _thumbs_up.html..erb
<div id = "like-<%= story.id %>" class="thumbs-up">
     <%= story.thumbs_up_total %>
 </div>

# _thumbs_down.html..erb
<div id = "like-<%= story.id %>" class="thumbs-down">
     <%= story.thumbs_down_total %>
 </div>

添加名为like.js

的文件
# like.js
$(".thumbs-up").html("<%= j(render("thumbs_up")) %>");
$(".thumbs-down").html("<%= j(render("thumbs_down")) %>");

在点击链接时会调用like.js。它将重新渲染您的部分并在点击时更新您的拇指计数。