2016-01-01 136 views
1

我有一組輸入,爲此我期望有一個大量的數據(對象列表),所以我希望將這個輸入的create/update動作包裝在ActiveRecord事務中。Rails - 擴展屬性方法

有型號Student,其中has_one Account

ACCOUNT_FIELDS=[:name, :surname, :email, :phone, :activated] 
    has_one :account, :as => :account_holder, autosave: true, :dependent => :destroy 
    validates_associated_extended :account 

    ACCOUNT_FIELDS.each do |action| 
    define_method action do 
     get_or_build_account.send(action) 
    end 
    setter_action = action.to_s + "=" 
    define_method setter_action do |arg| 
    get_or_build_account.send(setter_action, arg) 
    end 
    end 

在這裏我做了一個讀/寫器的方法,所以@student.name將從帳戶返回相關的數據,還我可以通過@student得益於其分配給autosave

問題:正如我所說,我希望它被包裹在事務中,所以在我的控制器中我不保存任何東西。每個學生都是這樣分配的

student.attributes = #...data 

那裏的學生後來交給了交易塊。

但是!對於此特定型號,我想student.attributes也返回ACCOUNT_FIELDS的字段。

通常它與student.account_attributes一起工作,但正如我所說,後來student在事務處理,它是與模塊,我希望可以重用一些其他模型(它不需要這個邏輯)。

因此而不是修改我的模塊代碼的一些情況,我想這個模型的實例返回所需帳戶字段時,只是叫self.attributes

@student.attributes #=> :school_id => 1, :name => "John"... 

其中名稱是self.nameself.account.name

回答

0

嘗試這個:

def attributes 
    new_attributes={} 
    ACCOUNT_FIELDS.each do |field| 
    new_attributes[field]=self.send(field) 
    end 
    super.merge(new_attributes) 
end