Rails:没有路由匹配[POST]嵌套资源

时间:2017-12-04 11:03:31

标签: ruby-on-rails

在routes.rb中,我有这个嵌套资源

# OBSERVATIVE SESSIONS
resources :observative_sessions do
# OBSERVATIONS
  resources :observations
end

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

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

我无法理解我做错了什么。 谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

当你说POST observation_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.buildObservation.new(observation_session: @observation_session)。你应该避免设置这样的ID。