我有一个问题模型和一个答案模型。在问题显示视图中,我使用循环显示给定问题的所有答案。我想对这些答案进行投票。我正在使用acts_as_votable gem。
这是我在加载“/ questions / 1”时遇到的错误:
No route matches {:action=>"upvote", :controller=>"answers", :id=>nil, :question_id=>"1"} missing required keys: [:id]
似乎答案:id未被检测到,因此它没有找到匹配的路线(例如/ questions / 1 / answers / 1 / like)。我在这里做错了什么?
奇怪的是,使用相同的代码,投票在Answers索引视图中完美运行。所以我怀疑这是通过问题控制器和视图尝试使用此代码。这可能是一个明显的问题,但感谢任何提示!
我的嵌套路线:
resources :questions do
resources :answers do
member do
put 'like', to: 'answers#upvote'
put 'dislike', to: 'answers#downvote'
end
end
end
我的答案控制器 - upvote / downvote行动:
def upvote
@question = Question.find(params[:question_id])
@answer = @question.answers.find(params[:id])
@answer.upvote_by current_user
redirect_to question_answers_path(@question)
end
def downvote
@question = Question.find(params[:question_id])
@answer = @question.answers.find(params[:id])
@answer.downvote_by current_user
redirect_to question_answers_path(@question)
end
我的问题显示视图(最终我会将其视为部分)
<% @question.answers.each do |answer| %>
<li class="answer-item">
<div class="answer-description">
<%= answer.description %>
</div>
<div class="vote">
<div class="col-xs-3">
<%= link_to 'UP', like_question_answer_path(@question, answer), method: :put %>
</div>
<div class="col-xs-9">
</div>
</div>
</li>
我的路线:
like_question_answer PUT /questions/:question_id/answers/:id/like(.:format) answers#upvote
dislike_question_answer PUT /questions/:question_id/answers/:id/dislike(.:format) answers#downvote
question_answers GET /questions/:question_id/answers(.:format) answers#index
POST /questions/:question_id/answers(.:format) answers#create
new_question_answer GET /questions/:question_id/answers/new(.:format) answers#new
edit_question_answer GET /questions/:question_id/answers/:id/edit(.:format) answers#edit
question_answer GET /questions/:question_id/answers/:id(.:format) answers#show
PATCH /questions/:question_id/answers/:id(.:format) answers#update
PUT /questions/:question_id/answers/:id(.:format) answers#update
DELETE /questions/:question_id/answers/:id(.:format) answers#destroy
questions GET /questions(.:format) questions#index
POST /questions(.:format) questions#create
new_question GET /questions/new(.:format) questions#new
edit_question GET /questions/:id/edit(.:format) questions#edit
question GET /questions/:id(.:format) questions#show
PATCH /questions/:id(.:format) questions#update
PUT /questions/:id(.:format) questions#update
DELETE /questions/:id(.:format) questions#destroy
答案 0 :(得分:0)
No route matches {:action=>"upvote", :controller=>"answers", :id=>nil, :question_id=>"1"} missing required keys: [:id]
此错误消息告诉您需要知道的一切。当您在答案视图中时,id
(答案ID)正在传递给Answers控制器,但是当您在问题视图中时,没有答案ID来填充请求的该参数。因为参数不存在,所以它与路线的正则表达不匹配。
PUT questions/1/answers/1/like
必须包含作为请求一部分的ID。
修改强> 假设您有一个现有的问题和答案记录。如果更改以下行,是否会出错?
<%= link_to 'UP', like_question_answer_path(Question.first, Answer.first), method: :put %>