我试图链接以添加编辑测验链接我的Rails应用程序,但我得到这个错误:没有路线匹配{:action =>“edit”,:controller =>“quiz_bs”,:id => nil}缺少必需的键:[:id]
No route matches {:action=>"edit", :controller=>"quiz_bs", :id=>nil} missing required keys: [:id]
我已经看过类似的帖子(like this one),但他们的答案似乎并没有解决问题,即使他们提出类似的情况。
错误是出现了此行的我application.html.erb
代码:
<li>
<% if @user.quiz_bs == nil %>
<%= link_to "Body Structure Quiz", quiz_bs_path %>
<% else %>
<%= link_to "Body Structure Quiz ✓", edit_quiz_b_path(id: @user.quiz_bs) %>
<% end %>
</li>
但链接也将是我的节目的用户页面上:
<h4>Body Structure</h4>
<% if @user.quiz_bs == nil %>
<p><%= link_to "Test Your Body Structure", new_quiz_b_path %></p>
<% else %>
<h3><%= @user.quiz_bs.bscode %></h3>
<p><%= link_to "Retest Results", edit_quiz_b_path(id: @quiz_bs.id) %></p>
<% end %>
这里是我的quiz_bs_controller
:
class QuizBsController < ApplicationController
before_action :require_sign_in
def show
@quiz_bs = QuizBs.find(params[:id])
end
def new
@quiz_bs = current_user.quiz_bs || current_user.build_quiz_bs
end
def create
@quiz_bs = QuizBs.new
@quiz_bs.bs01 = params[:quiz_bs][:bs01]
@quiz_bs.bs02 = params[:quiz_bs][:bs02]
@quiz_bs.bs03 = params[:quiz_bs][:bs03]
@quiz_bs.bs04 = params[:quiz_bs][:bs04]
@quiz_bs.bs05 = params[:quiz_bs][:bs05]
@quiz_bs.bs06 = params[:quiz_bs][:bs06]
@quiz_bs.user = current_user
if @quiz_bs.save
flash[:notice] = "Quiz results saved successfully."
redirect_to user_path(current_user)
else
flash[:alert] = "Sorry, your quiz results failed to save."
redirect_to welcome_index_path
end
end
def edit
@quiz_bs = QuizBs.find(params[:id])
@quiz_bs.assign_attributes(quiz_bs_params)
if @quiz_bs.save
flash[:notice] = "Post was updated successfully."
redirect_to user_path(current_user)
else
flash.now[:alert] = "There was an error saving the post. Please try again."
redirect_to welcome_index_path
end
end
def update
@quiz_bs = QuizBs.find(params[:id])
@quiz_bs.assign_attributes(quiz_bs_params)
if @quiz_bs.save
flash[:notice] = "Post was updated successfully."
redirect_to user_path(current_user)
else
flash.now[:alert] = "There was an error saving the post. Please try again."
redirect_to welcome_index_path
end
end
private
def quiz_bs_params
params.permit(:bs01, :bs02, :bs03, :bs04, :bs05, :bs06)
end
end
而相应的路线是:
quiz_bs GET /quiz_bs(.:format) quiz_bs#index
POST /quiz_bs(.:format) quiz_bs#create
new_quiz_b GET /quiz_bs/new(.:format) quiz_bs#new
edit_quiz_b GET /quiz_bs/:id/edit(.:format) quiz_bs#edit
quiz_b GET /quiz_bs/:id(.:format) quiz_bs#show
PATCH /quiz_bs/:id(.:format) quiz_bs#update
PUT /quiz_bs/:id(.:format) quiz_bs#update
我会很感激任何帮助找出问题在这里!
'<%= link_to“Body Structure Quiz✓”,edit_quiz_b_path(id:@quiz_bs.id)%>' – 7urkm3n
在application.html.erb页面中,@quiz_bs的值为零,因为它给出了错误 –
请注意:'edit'方法不应该做任何处理,它只是负责渲染页面。所以,你只需要'@quiz_bs = QuizBs.find(params [:id])',就这些了。 – GoGoCarl