1
我有一個模型與另一個嵌套屬性。最佳實踐的嵌套屬性
我的問題是:如何在控制器或模型中調用構建的更好的解決方案?
請參閱模型:
class ContentType < ActiveRecord::Base
after_initialize :add_fields
belongs_to :project
has_many :field_content_types
accepts_nested_attributes_for :field_content_types, reject_if: proc {|attributes| attributes['name'].blank?}
private
def add_fields
self.field_content_types.build if new_record?
end
end
要麼刪除after_initialize
模型,並添加行控制器
class ContentTypesController < ApplicationController
def new
@content_type = ContentType.new
@content_type.field_content_types.build
end
end
有一個理由來設置建立控制器?
謝謝@ jason-kim!但在測試中,控制器很多模擬,因爲'field_content_types'也有很多選項,並且是嵌套屬性。這是正確的? –
我不太明白你的問題。當你說很多嘲弄的時候,你是說你正在用'if new_record'來構建'field_content_types'?現在如果是這樣的話,我認爲在模型中編寫這個方法是有意義的,因爲你不想重複你自己每次寫'if'語句。 –
非常感謝Jason :) –