2016-01-01 210 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