1

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

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

2 回答 2

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 将被调用。它将重新渲染您的部分并在点击时更新您的拇指计数。

于 2015-08-05T15:11:43.010 回答
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>
于 2015-08-05T14:25:33.497 回答