Upvotes不工作
我正试图通过使用acts_as_votable gem来解决问题。 我收到的错误是:
Couldn't find Question with id=like
此url未显示问题ID:
/comments/1/questions//like
当我手动输入问题ID时,它给了我这个:
No route matches [GET]
这是我的upvote方法:
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按钮:
Rake路由将comment_question_like_path显示为有效路由,因此不是问题。 谢谢你的帮助!
你是说你在页面上/comments/2/questions
,这意味着你正处于questions#index
action中你加载当前评论的所有问题,然后你用@questions.each do |question|
一个循环的@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
和问题param没有设置,应该是: /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
路线method: post
到链接。
从这里开始跟进: acts_as_votable gem routes错误
对不起,以前我不完全理解,现在就试试吧:
的routes.rb
resources :comments do resources :questions do member do post "like", to: "questions#upvote" end end end
在您的upvote方法中(假设问题和评论在模型中相关)
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 %>
尝试使用以下代码。
在你的路线
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