我創建了一個 R-o-R 表單物件,該物件接收屬性,然后將這些屬性保存到一些嵌套物件中,然而,在驗證失敗后,輸入值就會消失。有什么辦法可以保留它們嗎?
class FormObject
include ActiveModel::Model
attr_accessor(:name, :date)
def initialize(params = {})
@params = params
end
def save
return if invalid?
no = NestedObject.new(nested_object_params)
no.save
end
def nested_object_params>>
@params.permit(:name, :date)
end
結束。
而這是控制器
class Controller
def new
@form = FormObject.new
end @form = FormObject.new
def create
@form = FormObject.new(form_object_params)
if @form.save
redirect_to ...
else
渲染:new。
end
end
def form_object_params>>
params.require(:form_object).allow(:name, :date)
end
結束。
uj5u.com熱心網友回復:
問題很可能是你多載了初始化方法而沒有呼叫super。這擾亂了由ActiveModel::AttributeAssignment完成的整個屬性映射,而表單真正依賴的是能夠獲取模型的屬性。
class FormObject
include ActiveModel::Model
attr_accessor(:name, :date)
def initialize(params = {})
@params = params
super
end end
def save
return if invalid?
no = NestedObject.new(nested_object_params)
no.save
end
def nested_object_params>>
@params.permit(:name, :date)
end
結束。
如果你使用ActiveModel::Attributes而不是Ruby內置的attr_accessor,你會得到型別轉換,就像使用ActiveRecord支持的屬性。
但這是一個直接的災難,因為你現在有三個相同資料的不同表示:
但這是一個直接的災難。
- 你的 FormObject 上的實體變數 。
- 存盤在 @params 中的哈希值 。
- 存盤在 NestedObject 中的屬性 。
相反,你可能應該完全重新考慮這個問題,并使用委托:
class FormObject
include ActiveModel::Model
attr_accessor :object
委托 :name, :name=, :date, : date=, :save, to: :object.
def intialize(**attributes)
@object = NestedObject.new(attribute)
super
end end
end end
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/313859.html
標籤:
