[英]How to edit a pre-existing model to add a newly created associated class?
我在實時應用程序中有一套公寓 object。 我決定為每個公寓添加一個相關的便利設施 object 來描述公寓有哪些便利設施。 便利設施 model 顯示
class Amenity < ApplicationRecord
belongs_to :apartment
end
公寓 model 展示
class Apartment < ApplicationRecord
has_one :amenity, dependent: :destroy
accepts_nested_attributes_for :amenity
end
使用相關設施創建新公寓效果很好公寓 controller 顯示
def new
@apartment = Apartment.new
@apartment.build_amenity
end
一旦使用便利設施創建公寓,就可以輕松編輯便利設施公寓 controller 顯示
def edit; end
但是,對於現有公寓,編輯表單不會顯示要填寫的便利設施(很可能是因為沒有與現有公寓相關聯的預先創建的便利設施)。 我嘗試更改 controller 中的編輯操作如下
def edit
@apartment = Apartment.find_or_initialize_by(params[:id])
end
def edit
@apartment = Apartment.find_or_create_by(params[:id])
end
但是這兩個選項都不能顯示表單。 The form works well when creating brand new apartment with associated amenities so there is something in the controller missing (an equivalent of @apartment.build_amenity in the edit controller that would instantiate a new amenity object associated with pre-existing apartment that I want to edit )。 你能幫我解決這個問題嗎?
這是表單代碼(非常基本)
<%= form.fields_for :amenity, @apartment.amenity do |p| %>
...
<% end %>
要編輯現有的apartment
,您可以使用includes
預加載amenity
def edit
@apartment = Apartment.includes(:amenity).find_or_initialize_by(id: params[:id])
end
通知
<%= form.fields_for :amenity, (@apartment.amenity || @apartment.build_amenity) do |p| %>
我通過將 false 作為默認值直接添加到表中來解決了這個問題
create_table "amenities", force: :cascade do |t|
t.boolean "towels", default: false
t.boolean "bed_linen", default: false
t.boolean "toilet_paper", default: false
t.boolean "soap", default: false
...
默認情況下具有 false 值而不是 nil 可以使表單出現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.