Rails form_for 错误 |如何将嵌套的 ActiveRecord 对象绑定到表单

Rails form_for Error | How to Bind Nested ActiveRecord Object to Form

我正在 Rails 应用程序上开发 Ruby。它有一个像这样的嵌套路由:

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_controllernewedit 操作如下:

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 无法找出 newedit 路径的正确 URL。即使在 edit 页面上,它也始终显示新表单。

我该如何解决这个问题?

提前致谢!

It always shows a new form even on edit page

我想问题出在你的 edit 方法中的这一行 @place = @trip_plan.places.build

@place = @trip_plan.places.build 只不过是 @place = @trip_plan.places.new,所以 Rails 对待 @place 作为 新实例 甚至 编辑表单

将其更改为 @place = Place.find(params[:id]) 应该可以解决您的问题。

更新:

您还应该更改以下内容

= form_for @place do |f|

= form_for [@trip_plan, @place] do |f|