[英]Rails: No route matches [POST] nested resources
在routes.rb中,我有此嵌套資源
# OBSERVATIVE SESSIONS
resources :observative_sessions do
# OBSERVATIONS
resources :observations
end
在observations_controller.rb中
def new
@observative_session = ObservativeSession.find(params[:observative_session_id])
@observation = Observation.new
@observation.observative_session_id = @observative_session.id
end
def create
@observative_session = ObservativeSession.find(params[:observative_session_id])
@observation = @observative_session.observations.build(observation_params)
@observation.user_id = current_user.id
respond_to do |format|
if @observation.save
format.html { redirect_to [@observative_session, @observation], notice: 'Observation was successfully created.' }
format.json { render :show, status: :created, location: @observation }
else
format.html { render :new }
format.json { render json: @observation.errors, status: :unprocessable_entity }
end
end
end
在observations_controller_test.rb中,我設置了觀察和觀察性會話。 新作品的測試就很好。
class ObservationsControllerTest < ActionDispatch::IntegrationTest
include Devise::Test::IntegrationHelpers
setup do
@observative_session = observative_sessions(:one)
@observation = observations(:two)
sign_in users(:admin_user)
end
test "should get new" do
get new_observative_session_observation_path(@observative_session)
assert_response :success
end
test "should create observation" do
assert_difference('Observation.count') do
post observative_session_observation_path(@observative_session, @observation), params: { observation: { start_time: @observation.start_time, description: @observation.description, rating: @observation.rating, notes: @observation.notes, celestial_body_name: @observation.celestial_body_name, telescope_name: @observation.telescope_name, binocular_name: @observation.binocular_name, eyepiece_name: @observation.eyepiece_name, filter_name: @observation.filter_name, user_id: @observation.user_id, observative_session_id: @observation.observative_session_id }}
end
但這是我在創建測試中遇到的錯誤
test_should_create_observation
ActionController::RoutingError: No route matches [POST] "/observative_sessions/980190962/observations/298486374"
我不明白我在做什么錯。 謝謝你的幫助。
當您說POST observation_session_observation_path(@observation_session, @observation)
您是在告訴它在參數中同時具有:observation_session_id
和:id
的URL,其中id
是@obseravtion
的id
。 但是,用於create
操作的POST路徑不會采用最后一個id
參數(表面上您正在使用該操作創建新記錄)。
嘗試從路徑助手中刪除@observation
(並確保使用正確的創建路徑: observation_session_observations_path(@observation_session)
。您可以通過rake routes
路由在終端或localhost:3000/rails/info/routes
查看localhost:3000/rails/info/routes
在瀏覽器中看到它。
我還在您的new
操作中看到您正在手動分配observation_session_id
。 我建議您要么做以后做的事,然后調用@obervation_session.observations.build
Observation.new(observation_session: @observation_session)
,要么調用Observation.new(observation_session: @observation_session)
。 您應該避免這樣設置id。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.