【问题标题】:How to define upvote/downvote when using acts_as_votable for comments?使用acts_as_votable 进行评论时如何定义upvote/downvote?
【发布时间】:2014-10-15 17:44:16
【问题描述】:

我的 cmets 资源嵌套在我的帖子资源中,并且这两个资源都是 act_as_votable。

我将如何定义赞成/反对票?这是我现在的做法(cmets 控制器):

def upvote
    @post = Post.find(params[:id])
    @comment = @post.comment.find(params[:post_id])
    @post.upvote_by current_user
    redirect_to posts_path
end

   def downvote
     @post = Post.find(params[:id])
     @comment = @post.comment.find(params[:post_id])
     @post.downvote_by current_user
     redirect_to posts_path
   end

这是新的并创建动作和参数:

def new
    @post = Post.find(params[:post_id])
    @comment = Comment.new(params[:id])
 end


def create
  @post = Post.find(params[:post_id])
  @comment = @post.comments.create(comment_params)
  @comment.post_id = @post.id 
if @comment.save
  redirect_to @post
else

  redirect_to new_post_comment_path(post)
end
end

private

   def comment_params
      params.require(:comment).permit(:body, :post_id)

结束

这是我收到的错误消息:

 No route matches {:action=>"upvote", :controller=>"comment", :format=>nil, :id=>nil, 
 :post_id=>#<Comment id: 22, body: "test", user_id: 1, post_id: 4, created_at:         

 "2014-10-14 07:28:22", updated_at: "2014-10-14 07:28:22", cached_votes_total: 0,       

 cached_votes_score: 0, cached_votes_up: 0, cached_votes_down: 0,   

 cached_weighted_score: 0, cached_weighted_total: 0, cached_weighted_average: 0.0>} 
 missing required keys: [:id]

我的嵌套路线:

  resources :posts do
member do
  put "like", to: "posts#upvote"
  put "dislike", to: "posts#downvote"
end
resources :comments do
member do
  get 'upvote' => 'comment#upvote', as: :upvote
  get 'downvote' => 'comment#downvote', as: :downvote
end
end
end

cmets/index.html.erb:

<div class="comments">
<% @comments.each do |comment| %>
<p><%= comment.body %></p>


<div>
  <%= link_to "up", upvote_post_comment_path(comment) %>
  <%= link_to "down", downvote_post_comment_path(comment) %>
  <%= comment.score %>
</div>
<% end %>
</div>

【问题讨论】:

  • 欢迎来到 SO!我在这里看到两个问题。首先,一个设计问题:upvote 和 downvote 动作应该在哪里进行,即。它们应该是 cmets 控制器中的非资源性操作吗?二、路由问题:如何为新动作添加路由?您希望我们关注哪个问题? :)
  • 路由问题、错误信息以及我的非资源操作是否设置正确。
  • 路由文件的相关部分是什么样的?
  • 添加了相关路由。

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


【解决方案1】:

我认为这里的关键是“无路由匹配”错误末尾的这个提示:

missing required keys: [:id]

我猜你的 Comment 对象有一个 nil id。可能还没有持久化?

另外,可能不相关,你有一条不明确的路线:

resources :comments do
  member do
    get 'upvote' => 'comment#upvote', as: :upvote
    get 'upvote' => 'comment#downvote', as: :downvote
  end
end

了解/comments/:id/upvote 如何路由到两个不同的操作?

【讨论】:

  • 我修复了双重投票路线,谢谢。我知道 :id 为零,但我不知道出了什么问题。我应该使用哪些调试工具或查看资源?
  • 可能是赞成/反对的链接被破坏(特别是它的 ID 部分)。请给我链接好吗?
  • 我认为upvote_post_comment_path 有两个参数,帖子和评论。看看它是如何尝试将您的评论实例用作post_id
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-28
  • 1970-01-01
  • 1970-01-01
  • 2016-06-04
  • 1970-01-01
  • 2013-12-24
  • 1970-01-01
相关资源
最近更新 更多