如果我們的模型如下:
class Book < ApplicationRecord
has_many :chapters
end
class Chapter < ApplicationRecord
belongs_to :book
end
路線:
resources :books do
resources :chapters
end
我們要創建一個表單:
<%= form_with(url: new_book_chapter_url(chapter) do |f| %>
/books/:id/chapters/new我們如何在不設定bookid的情況下創建這種表單 ( ) ?
上面的例子會拋出:
No route matches {:action => "new",
:book_id => nil,
:controller => "chapter"},
missing required keys: [:book_id]
在我的情況下,用戶book在表單中設定了希望,我希望它是blank在表單出現時
uj5u.com熱心網友回復:
這里有幾個問題,我認為您實際上并沒有理解 Rails 中 RESTful 路由的基礎知識或嵌套路由的用途。
如果您想創建一個章節而不在表單操作中指定書籍,那么您不應該使用嵌套路由。只需宣告一個非嵌套路由。
resources :chapters, only: [:create]
<%= form_with(model: chapter) do |f| %>
<div class="field">
<%= f.label :book_id, "Select a book" %>
<%= f.collection_select :book_id, Book.all, :id, :name %>
</div>
<% end %>
創建資源時,您 ??POST 到集合路徑 ( /chapters) 而不是 ( /chapters/new)。Rails 中的newandedit動作僅用于顯示表單。這適用于嵌套和非嵌套路由。
您還應該使用該model選項,讓 Rails 從傳遞的記錄中推斷出路線。url僅當您必須打破約定或使用沒有模型的表單時才應使用。
看:
- https://guides.rubyonrails.org/routing.html#crud-verbs-and-actions
- https://guides.rubyonrails.org/routing.html#nested-resources
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/431892.html
標籤:轨道上的红宝石 红宝石 形式 ruby-on-rails-6 嵌套资源
