Per this pull request我可以看到一个数组应该传递给form_with
的模型参数。但是,当我提供以下内容时:
<%= form_with(model: [@trip, @activity], local: true) do |f| %>
...
<% end %>
Rails将返回 - ActionView::Template::Error (undefined method activity_path' for #<#<Class:0x007f80231e3070>:0x007f8023010dd8>):
我的路线文件如下:
resources :trips do
resources :activities
end
rake routes
的输出看起来像 -
trip_activities GET /trips/:trip_id/activities(.:format) activities#index
POST /trips/:trip_id/activities(.:format) activities#create
new_trip_activity GET /trips/:trip_id/activities/new(.:format) activities#new
edit_trip_activity GET /trips/:trip_id/activities/:id/edit(.:format) activities#edit
trip_activity GET /trips/:trip_id/activities/:id(.:format) activities#show
PATCH /trips/:trip_id/activities/:id(.:format) activities#update
PUT /trips/:trip_id/activities/:id(.:format) activities#update
DELETE /trips/:trip_id/activities/:id(.:format) activities#destroy
trips GET /trips(.:format) trips#index
POST /trips(.:format) trips#create
new_trip GET /trips/new(.:format) trips#new
edit_trip GET /trips/:id/edit(.:format) trips#edit
trip GET /trips/:id(.:format) trips#show
PATCH /trips/:id(.:format) trips#update
PUT /trips/:id(.:format) trips#update
DELETE /trips/:id(.:format) trips#destroy
我的activities_controller.rb -
before_action :set_activity, only: %i[show update edit destroy]
def edit; end
def update
dates = calculate_datetimes(params[:date_range])
@activity.assign_attributes(name: params[:name],
summary: params[:summary],
start_datetime: dates[0],
end_datetime: dates[1])
if @activity.save
flash[:success] = 'Activity successfully updated'
redirect_to(@trip)
else
set_humanized_daterange
render :edit
end
end
private
def set_activity
@activity = Activity.find(params[:id])
end
tl; dr - 我应该如何为嵌套资源设置form_with,为什么这个表单认为我想使用activity_path
?理想情况下,我希望将此表单移动到部分表单中,并对我的#new和#edit操作使用相同的表单。
答案 0 :(得分:24)
尝试单独指定模型和网址:
form_with(model: @activity, url: [@trip, @activity])
根据文档,url
的值是“类似于传递给url_for或link_to的值”,因此使用数组应该有效。
为了支持浅嵌套,您可以像这样使用条件:
form_with(model: @activity, url: (@activity.new_record? ? [@trip, @activity]: @activity))
答案 1 :(得分:4)
您只需要将网址添加到您希望表单指向的路由中,即:, url: trip_activity_path
或您正在尝试的路径
答案 2 :(得分:2)
添加到max answer,如果您想支持浅嵌套,您还可以使用:
form_with(model: [@trip, @activity])
更改edit.html.erb上的渲染,将nil传递给trip,例如:
<%= render 'form', trip: nil, activity: @activity %>
并保持它在你的new.html.erb中传递旅行模型
答案 3 :(得分:0)
更改url很好,但是您可以改为更改模型,该模型允许构建器推断url和任何作用域等:
<%= form_with(model: child.new_record? ? [@parent, child] : child, local: true) do |form| %>
新/编辑视图:<%= render 'form', child: @child %>
控制器将需要从url参数中设置@parent,无论如何这都是嵌套资源的约定。