这是具有类似操作的控制器:
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>