首页 > 解决方案 > Rails 中没有路线匹配 [POST]

问题描述

提交表单时出现路由错误

resources :sellers do
    resources :seller_profiles
end
<%= form_for seller_seller_profiles_path do |form| %>
  <div class="field">
    <%= form.label :first_name %>
    <%= form.text_field :first_name %>
  </div>

  <div class="field">
    <%= form.label :other_name %>
    <%= form.text_field :other_name %>
  </div>

   -- more similar fields ---

  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>
 def create 
    @seller_profile = @seller.seller_profile.create!(seller_profile_params)

    respond_to do |format|
      format.html { redirect_to root_path}
    end

错误消息:在 2021 年 1 月 11 日 21:37:01 +0000 开始为 ::1 发布“/sellers/1/seller_profiles/new”

ActionController::RoutingError (没有路由匹配 [POST] "/sellers/1/seller_profiles/new"):

更新

我将视图更改为

<%= form_with(model: [@seller, @seller_profile], local: true) do |form| %>
--- code continues ---

现在新路线有效,但编辑路线抛出此错误 ActionView::Template::Error (undefined method `seller_profile_path' for #ActionView::Base:0x0000000001d060 你的意思是?seller_path):

标签: ruby-on-rails

解决方案


而是传递模型实例,以便您的输入绑定到模型实例。对于嵌套资源,传递一个数组:

<%= form_for([@seller, @seller_profile]) do |form| %>

这可确保输入将包含验证失败时用户输入的值。它还连接到 I18n API 进行翻译,因此它将使用该模型的翻译键而不是通用键。

如果您使用的是 Rails 5.1+,请form_with(model: [@seller, @seller_prodile], local: true)改用。


推荐阅读