评论和投票的路线 [英] Routes on comments and votes

查看:57
本文介绍了评论和投票的路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型可以评论,书籍和电影.

I have two models that can be commented on, Books and Movies.

评论是可以投票的

在我的路由文件中:

 resources :books, :path => '' do
    resources :comments do
      member do
    post :vote_up
  end
end

在我的评论控制器中:

class CommentsController < ApplicationController
  def create
    book.comments.create(new_comment_params) do |comment|
      comment.user = current_user
    end
    redirect_to book_path(book)
  end

  private

  def new_comment_params
    params.require(:comment).permit(:body)
  end

  def book
    @book = Book.find(params[:book_id])
  end

  def vote_up
    begin
      current_user.vote_for(@comment = Comment.find(params[:id]))
      render :nothing => true, :status => 200
    rescue ActiveRecord::RecordInvalid
      render :nothing => true, :status => 404
    end
  end
end

在我看来:

    <%= link_to('vote for this post!', vote_up_book_comment_path(comment), 
:method => :post) %>

我不断收到此错误:

No route matches {:action=>"vote_up", :controller=>"comments", :id=>nil, :book_id=>#<Comment id: 
3, body: "fantastic read!", book_id: 113, created_at: "2014-02-15 17:08:10", updated_at: 
"2014-02-15 17:08:10", user_id: 8>, :format=>nil} missing required keys: [:id]

这是我用于投票的 gem:https://github.com/bouchard/thumbs_up

This is the gem I am using for the voting: https://github.com/bouchard/thumbs_up

评论可以属于书籍或电影,我如何在路由中设置?另外,如何在路线中设置投票?(所有评论都是可投票的)

The comments can belong to either the books or movies, how do I set this up in the routes? Also, how do I set up the votes in the routes? (all the comments are votable)

推荐答案

如果您运行 rake routes,您可能会在输出中看到如下一行:

If you run rake routes, you'll probably get a line in the output that reads like this:

vote_up_book_comment POST   /:book_id/comments/:id/vote_up(.:format) comments#vote_up

特别注意这部分——它告诉你 vote_up_book_comment_path 方法期望什么作为参数:

Pay special attention to this part — it's telling you what the vote_up_book_comment_path method expects as arguments:

/:book_id/comments/:id/vote_up(.:format)

此外,您的错误消息也给了您一些提示:

Also, your error message is giving you a few hints:

No route matches ...
:id=>nil, :book_id=>#<Comment id: 3 ...
missing required keys: [:id]

路径助手需要一个 id(用于评论)和一个 book_id,它们的顺序显示在 rake routes(首先是 book_id,然后是 id).

The path helper expects an id (for the comment) and a book_id, and the order in which they are required is shown in rake routes (book_id first, then id).

所以,总而言之,您需要将 book 传递给 vote_up_book_comment_path:

So, in sum, you need to pass a book to vote_up_book_comment_path:

<%= link_to('vote for this post!', vote_up_book_comment_path(@book, comment), :method => :post) %>

这篇关于评论和投票的路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆