如何添加 '+1' Rails 3 应用程序中的链接,单击后点赞值会增加 1?
我是编程新手。
我生成了一个创意脚手架。该模型具有字段:描述(字符串)、赞成票(整数)、反对票(整数)。
ideas_controller.rb 中的所有正常操作均有效 - 索引、显示、新建、编辑、创建、更新、销毁。
我不会告诉您我尝试执行以下操作的方法,而是会问:
如何在“显示”、“编辑”、“销毁”链接旁边添加“+1”链接,单击该链接会增加该想法的赞成票值为 1?
提前致谢。
编辑(在“Skydreamer”的帮助下,我想通了!)
我将routes.rb调整为:
resources :ideas do
member do
get 'upvote'
end
end
我将以下内容添加到想法index.html.erb中:
<td><%= link_to '+1', upvote_idea_path(idea) %></td>
注意:如果您不包括(想法),你会得到这样的错误:
没有路线匹配 {:action=>"upvote", :controller=>"ideas"}
我将以下内容添加到 ideas_controller.rb 中:
def upvote
@idea = Idea.find (params[:id])
@idea.upvotes = @idea.upvotes + 1
@idea.save
redirect_to(ideas_url)
end
I'm new to programming.
I generated an Ideas scaffold. The model has fields: Description (string), Upvotes (integer), Downvotes (integer).
All the normal actions in the ideas_controller.rb work - Index, Show, New, Edit, Create, Update, Destroy.
Instead of telling you the ways I've tried to do the following, I'll just ask:
How do I add a '+1' link next to the 'Show', 'Edit', 'Destroy' links that when clicked increases the Upvotes value by 1 for that idea?
Thanks in advance.
EDIT (With "Skydreamer's" help, I figured it out!)
I adjust the routes.rb to:
resources :ideas do
member do
get 'upvote'
end
end
I add the following to the ideas index.html.erb:
<td><%= link_to '+1', upvote_idea_path(idea) %></td>
Note: if you don't include the (idea), you'll get an error like this:
No route matches {:action=>"upvote", :controller=>"ideas"}
I add the following to the ideas_controller.rb:
def upvote
@idea = Idea.find (params[:id])
@idea.upvotes = @idea.upvotes + 1
@idea.save
redirect_to(ideas_url)
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在接下来的几行中,我会说“赞成”,但对于“反对”来说也是一样的。
首先,创建成员路由
upvote
,然后您可以使用upvote_idea_path
从显示视图链接到新操作。其次,在控制器中创建一个操作
upvote
,将投票数增加 1,然后就完成了。就这样。In the next lines, I'll say upvote but that works the same for downvote.
First, create a member route
upvote
, then you can link from your show view to the new action usingupvote_idea_path
.Second, create an action
upvote
in the controller which increases the vote count by 1 and you're done. That's all.您可以使用 thumbs_up gem 来实现此功能。它还兼容 Rails 3。
You can achieve this functionality with the thumbs_up gem. It is also Rails 3 compatible.