在注释控制器中不正确地生成:id(嵌套资源)

时间:2014-10-14 22:38:23

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

我正在尝试嵌套我的评论资源,并使用 acts_as_votable 为评论添加投票。我在尝试访问 post_comments_path 时收到此错误消息:

No route matches {:action=>"upvote", :controller=>"comments", :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] 

所以你可以看到我没有发表评论或发表:id ??

    class CommentsController < ApplicationController
   def index
     @comments = Comment.order('created_at desc')
   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


   def show
    @comment = Comment.find(params[:id])
   end

    def destroy
   end

   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

   private

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

这是我的post_comments_path视图(评论/ index.html,erb)

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


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

路由:

root 'static_pages#home'

  resources :posts do
   member do
     put "like", to: "posts#upvote"
    put "dislike", to: "posts#downvote"
   end
   resources :comments do
   member do
     put "like", to: "comments#upvote"
     put "dislike", to: "comments#downvote"
   end
 end
 end

1 个答案:

答案 0 :(得分:0)

没有50个评论,所以这里有一个简单的回答:

尝试在终端中运行rake routes并确认您的路线是否正常。

其次,操作是否向上/向下注册GET或POST请求?您还需要向我们展示您的routes.rb

第三,尝试一下宝石&#39; pry&#39;并在上/下操作的每一步调用binding.pry。通过这种方式,您可以检查每行代码,看看它是否按照您希望的方式运行。

最后,我认为在设计方面,将这些作为模型类的方法包含在内,而不是控制器动作可能是值得的 - 也许一些明智的RoR开发者可以阐明这一点。 / p>