【发布时间】:2015-07-12 11:49:04
【问题描述】:
我正在开发一个 Ruby on Rails 应用程序。它有一个像这样的嵌套路由:
Rails.application.routes.draw do
root 'trip_plans#index'
resources :trip_plans do
resources :places, except: [:show, :index]
end
end
trip_plans 资源具有 TripPlan 模型,places 资源具有 Place 模型。根据路由,new_trip_plan_place_path 是类似/trip_plans/:trip_plan_id/places/new 的路由。 views/places/new.html.haml 使用form_for 声明在当前trip_plan 中创建一个新位置:
- content_for :title do
%title Add a Place to Your Plan
%header.form-header
.container.form-container
.row
.col-xs-12
%h1 Add a Place
%hr
%article
%section
.container.form-container
= render 'form'
对应的edit.html.haml本质上是一样的,调用同一个_form.html.haml来渲染表单。
places_controller 的 new 和 edit 操作如下:
def new
@trip_plan = TripPlan.find(params[:trip_plan_id])
@place = @trip_plan.places.build
end
def edit
@trip_plan = TripPlan.find(params[:trip_plan_id])
@place = @trip_plan.places.build
end
_form.html.haml 像这样使用@place:
= form_for @place do |f|
但由于@place 是一个依赖的ActiveRecord 对象,Rails 无法找出new 和edit 路径的正确URL。即使在 edit 页面上,它也总是显示一个新表单。
我该如何解决这个问题?
提前致谢!
【问题讨论】:
-
尝试在
edit方法中将此行@place = @trip_plan.places.build更改为@place = Place.find(params[:id])。
标签: ruby-on-rails ruby ruby-on-rails-3 activerecord