0

我正在尝试对使用acts_as_votable gem 的问题进行投票。我收到一条错误消息:

Couldn't find Question with id=like

此 URL 不显示问题 ID:

/comments/1/questions//like

当我手动输入问题ID时,它给了我这个:

No route matches [GET]

这是我的投票方法:

def upvote
@question = Question.find params[:question_id]
@question.liked_by current_user
redirect_to @questions
end

这是 routes.rb 文件:

resources :comments do
  resources :questions do
    put :upvote, :on => :member, :as => :like
  end
end

和upvote按钮:

<%= link_to "Upvote", comment_question_like_path(@comment, @question), method: :post %>

Rake 路线将 comment_question_like_path 显示为有效路线,因此这不是问题。谢谢你的帮助!

4

3 回答 3

0

从这里跟进:acts_as_votable gem routes 错误

对不起,我以前没有完全理解,现在试试这个:

路线.rb

resources :comments do
  resources :questions do
     member do
        post "like", to: "questions#upvote"
     end
  end
end

在您的投票方法中(假设问题和评论与模型相关)

def upvote
  @question = Question.find params[:id]
  @question.liked_by current_user
  redirect_to comment_question_path(@question.comment, @question)
end

然后在视图中:

<%= link_to "Upvote", like_comment_question_path(@comment, @question), method: :post %>
于 2013-09-13T21:45:50.963 回答
0

尝试使用以下代码。

在您的路线中

resources :comments do
  resources :questions do
   put :upvote, :on => :member, :as => :like
  end
end

在你看来

<%= link_to "Upvote", like_comment_question_path(@comment, @question), method: :put %>

在您的控制器中

def upvote
  @question = Question.where('id = ? and comment_id = ?', params[:id], params[:comment_id]).first
  unless @question.blank? 
    @question.liked_by current_user
    redirect_to comment_question_path(params[:comment_id], @question)
  else
    flash[:error] = 'Question not found'
    redirect_to comment_questions_path(params[:comment_id])
  end
end
于 2013-09-14T04:59:20.463 回答
0

你是说你在 page 上/comments/2/questions,这意味着你正在questions#index加载所有问题以获取当前评论,并且你对所有问题进行循环,@questions.each do |question|因此每个问题的链接应该如下所示:

<%= link_to "Upvote", comment_question_like_path(@comment, question) %>

并不是:

<%= link_to "Upvote", comment_question_like_path(@comment, @question) %>

由于您没有@question可用的变量,这就是您有/comments/1/questions//like并且未设置问题参数的原因,应该是: /comments/1/questions/5/like.

编辑


它在我的应用程序中为我工作的方式,路线

resources :comments do
  resources :questions do
    member do
      get :upvote
    end
  end
end

链接

<%= link_to "Upvote", comment_question_upvote_path(@comment, question) %>

他们以您构建路线的方式,您需要指定method: post链接。

于 2013-09-27T07:09:38.620 回答