轨道中的简单投票系统

时间:2013-12-27 15:35:05

标签: ruby-on-rails ruby-on-rails-4

我想为帖子创建简单的upvote系统。我在模型中添加了列,这就是我的posts_controller现在的样子:

  def upvote
    @upvote = @post.upvote + 1
  end

不知道如何让它在视图中工作?我想创建为upvote添加+1的链接。 不知道如何处理路线。

2 个答案:

答案 0 :(得分:2)

你可以采取两种方法,普通的html动词或ajax。 ajax方式看起来像:

# view
link_to 'Upvote this thing!', upvote_post_path(post), remote: true

# routes
resources :posts do
  member do
    post :upvote
  end
end

# controller
def upvote
  @post.update_attributes(upvote: @post.upvote + 1)
  ... do some ajax-y rendering here, like highlighting or replacing html
end

另一种方式可以类似地工作,除了你在link_to上没有remote:true,你可能会看起来更像是:

def upvote
  @post.update_attributes(upvote: @post.upvote + 1)
  redirect_to show_post_path(@post)
end

答案 1 :(得分:0)

http://www.youtube.com/watch?v=GG-kCSx0taU

视频我曾经实施过我的视频。如果您需要显示总投票数,则只需运行vote.countvote.size

相关问题