_form.html.erb
<%= form_with(model: [@seller, @seller_profile], local: true) do |form| %>
<div class="field">
<%= form.label :first_name %>
<%= form.text_field :first_name %>
</div>
--- similar input structure ---
<div class="actions">
<%= form.submit %>
</div>
<% end %>
此视图在新路线上运行良好,但是,在编辑路线上会出现此错误ActionView::Template::Error(#ActionView:的未定义方法"seller_profile_path":Base:0x0000000001d060你是说?seller_path(:
错误很可能是因为@seller
为零。Rails在数组上调用#compact
,因此它等效于调用form_with(model: [@seller_profile])
,后者将查找非嵌套的路由助手。
您可以通过在控制器中设置@seller
来解决:
class SellerProfilesController < ApplicationController
before_action :set_seller
# ...
private
def set_seller
@seller = Seller.find(params[:seller_id])
end
end
或者通过使用浅嵌套来避免嵌套成员路由(显示、编辑、更新、销毁(:
# config/routes.rb
resources :sellers do
resource :seller_profiles, shallow: true
end
class SellerProfilesController < ApplicationController
before_action :set_seller, only: [:new, :index, :create]
# ...
private
def set_seller
@seller = Seller.find(params[:seller_id])
end
end