2013-07-16 137 views
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 

有一個理由來設置建立控制器?

回答

1

假設你問你應該在哪裏建立field_content_types,在這種特殊情況下,我認爲不管你是在模型還是控制器中構建它,都不重要。

經驗法則是保持控制器和模型脂肪,但構建方法已經非常簡潔,你不會從模型構建它很大益處。

就我個人而言,我只是把它建在控制器中。

+0

謝謝@ jason-kim!但在測試中,控制器很多模擬,因爲'field_content_types'也有很多選項,並且是嵌套屬性。這是正確的? –

+0

我不太明白你的問題。當你說很多嘲弄的時候,你是說你正在用'if new_record'來構建'field_content_types'?現在如果是這樣的話,我認爲在模型中編寫這個方法是有意義的,因爲你不想重複你自己每次寫'if'語句。 –

+0

非常感謝Jason :) –