轨道:没有路由与 [POST] 嵌套资源匹配



在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"  

我不明白我做错了什么。 感谢您的帮助。

当你说POSTobservation_session_observation_path(@observation_session, @observation)时,你是在告诉它发布到一个网址,参数中既有:observation_session_id又有:id,其中id@obseravtion。但是,create操作的 POST 路径不采用最后一个id参数(表面上您正在使用该操作创建新记录)。

尝试从路径帮助程序中删除@observation(并确保使用正确的创建路径:observation_session_observations_path(@observation_session)。 您可以rake routes在航站楼中查看路线,也可以localhost:3000/rails/info/routes在浏览器中查看路线。

我还在您的new操作中看到您正在手动分配observation_session_id。我建议你要么做你以后做的事情,打电话给@obervation_session.observations.build,要么Observation.new(observation_session: @observation_session)。您应该避免设置这样的 ID。

最新更新