帮助:在Rails中为现有帖子模型添加评级

时间:2010-01-23 08:44:34

标签: ruby-on-rails rating

我有一个标题的简单帖子模型:字符串和评级:整数,我想添加评价帖子的能力。到目前为止我已经

#Post controller   
def increase
 @post = Post.find(params[:id])
 @post.increment! :rating
 flash[:notice] = "Thanks for your rating."
 redirect_to @post
end

#Post show
<%= link_to "Rating", increase_post_path %>

#Routes
map.resources :posts, :member => { :increase => :put }

当我点击评分时,我会采取不明行动。当我添加@ post.increment时,我能够提高评分! :评级更新,但不是我创建自己的方法。任何建议?

3 个答案:

答案 0 :(得分:4)

如果您有标准路线说

map.resources :posts

您应该将其替换为:

map.resources :posts, :member => { :increase => :put }

这将为您的应用创建路径“increase_post_path”,方法为“put”。

答案 1 :(得分:1)

您需要将操作添加到routes.rb文件中。有关详细信息,请参阅this excellent guide

答案 2 :(得分:1)

如果有人有兴趣,这是我的解决方案。谢谢你的帮助。

#Views
<%= link_to post.rating, increase_post_path(post) %>

#Controller
def increase
  @post = Post.find(params[:id]).increment!(:rating)
  flash[:notice] = "Thanks for rating"
  redirect_to posts_url
end

#Routes
map.resources :posts, :member => { :increase => :put }

如果您想要一些适合自己的东西,这是有效的,不会被滥用。显然,将评级添加到您的网站,其他人可以无限次投票,这只是一个问题。

我建议使用Votefu,评分,甚至还有用户业力。作者很擅长制作example app