gpt4 book ai didi

ruby-on-rails - 带有 Rails 5.1 form_with 的嵌套资源

转载 作者:行者123 更新时间:2023-12-03 12:08:32 25 4
gpt4 key购买 nike

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

还有我的事件 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;博士 - 我应该如何为嵌套资源设置我的 form_with,为什么这个表单认为我想使用 activity_path ?理想情况下,我想将此表单移动到部分表单中,并为我的 #new 和 #edit 操作使用相同的表单。

最佳答案

尝试分别指定模型和网址:

form_with(model: @activity, url: [@trip, @activity])

根据文档, url 的值是“类似于传递给 url_for 或 link_to 的值”,因此使用数组应该可以工作。

这也适用于浅嵌套,因为数组是压缩的。

关于ruby-on-rails - 带有 Rails 5.1 form_with 的嵌套资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46919115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com