2012-06-21 27 views
0

假设我们以下类正确属性初始化时的属性由另一类包裹

class Foo < ActiveRecord::Base 
    attr_accessible :name, :bars, :bazs 

    def bars=(bars) 
    baz = [] 
    bars.each { |b| barz << Baz.new(bar:b, magic_number: 123) } 
    end 

    def bars 
    bazs.map(&:bar) 
    end 
end 

class Bar < ActiveRecord::Base 
    attr_accesible :name 
end 

class Baz < ActiveRecord::Base 
    attr_accesible :magic_number, :bar 
    has_one :bar 
end 

这是“轨道”的方式来声明一个初始化方法,以便当从散列创建一个Foo已bazs被初始化。例如

Foo.new(name:"foo", bars:[Bar.new(name:"b1"), Bar.new(name:"b2")]) 

不能使用after_initialize因为self[:bars]收益为零。另一个选项是覆盖initialize方法,但它不是由Rails文档推荐的,我不能使用barz=,因为初始化后barz返回nil,我不得不使用self[:barz]=。另一种选择是声明一个类构造方法,通过调用setter来进行正确的初始化,但它似乎不是Ruby方式(Foo.from(name:"foo", bars:[Bar.new(name:"b1"), Bar.new(name:"b2")]))。

感谢

+0

它是'attr_accessible:name,:bars,:barz','barz = []'和'bars.each {| b | barz << Baz.new(bar:b,magic_number:123)}'? –

回答

0

OK我终于做了申报一切,attr_accessible并重写initialize方法

class Foo < ActiveRecord::Base 
    attr_accessible :name, :bars, :bazs 

    def initialize(attributes = nil, options = {}) 
    super 
    self.bars = attributes[:bars] 
    end 

    def bars=(bars) 
    self.bazs = [] 
    self.bars.each { |b| self.bazs << Baz.new(bar:b, magic_number: 123) } 
    end 

    def bars 
    self.bazs.map(&:bar) 
    end 

end 

有一点要注意,我不知道的是,每次我需要叫它需要使用self.