带有 Rails 5.1 form_with 的嵌套资源 [英] Nested Resources w/ Rails 5.1 form_with
问题描述
根据 this pull request 我可以看到应该将一个数组传递给 form_with
的模型参数.但是,当我提供以下内容时:
Per this pull request I can see that an array should be passed to form_with
's model param. However, when I supply the following:
<%= form_with(model: [@trip, @activity], local: true) do |f| %>
...
<% end %>
Rails 将返回 - ActionView::Template::Error(未定义方法 activity_path' for #<#<Class:0x007f80231e3070>:0x007f8023010dd8>):
Rails will return - ActionView::Template::Error (undefined method activity_path' for #<#<Class:0x007f80231e3070>:0x007f8023010dd8>):
我的路由文件看起来像:
My routes file looks like:
resources :trips do
resources :activities
end
rake routes
的输出看起来像 -
The output of rake routes
looks like -
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
还有我的活动控制器.rb -
And my 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 操作使用相同的表单.
tl;dr - how should I setup my form_with for a nested resource, and why is this form thinking I want to use the activity_path
? Ideally I'd like to move this form into a partial and use the same form for both my #new and #edit actions.
推荐答案
尝试分别指定模型和网址:
Try specifying the model and url separately:
form_with(model: @activity, url: [@trip, @activity])
根据文档,url
的值是类似于传递给 url_for 或 link_to 的值",因此使用数组应该可以工作.
According the docs the the values for url
are "Akin to values passed to url_for or link_to" so using an array should work.
这也适用于浅嵌套,因为数组被压缩了.
This also works with shallow nesting since the array is compacted.
这篇关于带有 Rails 5.1 form_with 的嵌套资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!