我試圖鏈接以添加編輯測驗鏈接我的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