【发布时间】:2014-11-02 23:09:12
【问题描述】:
我正在尝试为用户实施一个评论系统,其中每个评论都可以被投票。我有一个模型 UpVote,它多态地属于多个模型,包括评论,而每个用户都有_很多评论。
UpVote 模型:
class UpVote < ActiveRecord::Base
belongs_to :voteable, polymorphic: true
end
评论模型:
class Comment < ActiveRecord::Base
belongs_to :user
has_many :up_votes, as: :voteable
end
用户模型:
class User < ActiveRecord::Base
has_many :comments
has_many :up_votes, as: :voteable
end
用户展示:我在错误所在的行周围加了星号。
<% @user.comments.each do |c| %>
<%= c.text %>
<%= c.username %>
<%= c.id %>
***<%= link_to "upvote", upvote_comment_path(c.id), method: :post, :class => "btn btn-small" %>***
<% end %>
评论控制器:
def upvote
@comment = Comment.find(params[:id])
UpVote.create!(voteable_id: params[:id], voteable_type: 'Comment')
redirect_to root_path
end
路线:
post 'comments/:id/upvote' => 'comments#upvote', as: 'upvote_comment'
但是当我在用户页面上为评论提交 UpVote 时,我收到以下错误:
ActionController::UrlGenerationError in Users#show
No route matches {:action=>"upvote", :controller=>"comments", :id=>nil} missing required keys: [:id]
link_to 似乎不接受c.id,这很奇怪,因为c.id 自己会正常打印@comment.id。我做错了什么?
赏金消息中的错误:我的意思是赏金消息中的“@comment.id”,而不是“@comment.up_vote.count”,但我似乎无法对其进行编辑。
【问题讨论】:
-
请在您的
config/routes.rb中显示为此操作定义的路线。 -
@spickermann 我把它贴在上面了。
标签: ruby-on-rails ruby ruby-on-rails-4 routing associations