2

我有一个带有 title:string 和 rating:integer 的简单帖子模型,我想添加对帖子进行评分的功能。到目前为止我有

#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 时,我可以提高评分!:rating 更新,但不是在我创建自己的方法时。有什么建议吗?

4

3 回答 3

4

如果你有一条标准路线说

map.resources :posts

您应该将其替换为:

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

这将为您的应用创建带有方法“put”的路由“increase_post_path”。

于 2010-01-23T09:01:46.820 回答
1

您需要将操作添加到routes.rb文件中。有关详细信息,请参阅此出色的指南

于 2010-01-23T08:48:26.597 回答
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,进行评分,甚至有用户业力。作者很好地制作了一个示例应用程序

于 2010-01-23T10:02:52.380 回答