【问题标题】:Rails form_for Error | How to Bind Nested ActiveRecord Object to FormRails form_for 错误 |如何将嵌套的 ActiveRecord 对象绑定到表单
【发布时间】: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_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 页面上,它也总是显示一个新表单。

我该如何解决这个问题?

提前致谢!

【问题讨论】:

  • 尝试在edit 方法中将此行@place = @trip_plan.places.build 更改为@place = Place.find(params[:id])

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord


【解决方案1】:

即使在编辑页面上也总是显示一个新表单

我猜问题出在你的 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|

【讨论】:

  • 真棒帕万,它的工作原理。但编辑表单的action 仍设置为new_trip_plan_place_path,例如/trip_plans/1/place.
  • @AbraarArique 我没明白。你说的行动是什么意思仍然设置为new_trip_plan_place_path。你打算如何编辑表格?通过链接?
  • 我的意思是新的地点表单应该通过 POST 将其数据提交给/trip_plans/:trip_plan_id/places,而编辑表单应该通过 PATCH/PUT 请求提交给/trip_plans/:trip_plan_id/places/:id。但是当我访问表单页面(新的或编辑的)时,它会出错“未定义的方法places_path”。
  • 我认为这是因为通过将@place = Place.find(params[:id]) 定义为Rails 将@place 视为一个完全独立的ActiveRecord 对象,因此尝试通过POST 将数据提交到places_path,它认为/places 之类的东西。但实际上路由是通过trip_plans嵌套的,所以@place的每个URL都以trip_plans/:trip_plan_id为前缀。
猜你喜欢
  • 1970-01-01
  • 2017-03-04
  • 1970-01-01
  • 2013-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多