Ruby on rails 重写ActiveRecord集合(关联)方法

Ruby on rails 重写ActiveRecord集合(关联)方法,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,我是Ruby的新手,我正在尝试创建一个模型,在这个模型中,如果集合不存在,则会对它们进行组装 我已经重载了单个属性,如下所示: class My_class < ActiveRecord::Base def an_attribute tmp = super if tmp tmp else #calculate this and some similar, associated attributes, for example:

我是Ruby的新手,我正在尝试创建一个模型,在这个模型中,如果集合不存在,则会对它们进行组装

我已经重载了单个属性,如下所示:

class My_class < ActiveRecord::Base
  def an_attribute
    tmp = super
    if tmp
      tmp
    else
      #calculate this and some similar, associated attributes, for example:
      self.an_attribute = "default" #{This does work as it is calling an_attribute=() }
      self.an_attribute
    end
  end
end

test = My_class.new
p test.an_attribute # => "default"
class My\u class“默认”
这非常有效,基本上为我提供了| |=功能

因此,我不假思索地为自己编写了一个相当大的函数来对集合执行同样的操作(即,如果集合中没有对象,那么就去确定它们应该是什么)

class My\u classself.things确切的错误是什么?此外,考虑第一类方法的代码,如代码>Self.AnAtgult=超标“默认”/COD>,只需要一行。D//RuY193/LIB/Ruby/GEMs/1.91/GEMS/ActudiMeld- 3.1.3/LIB/ActuvyMault/AdvestyToRead。RB:385:在<代码>方法>缺少::Super:没有超类方法< /代码>的东西(NoththoDoRror)来自d:/Ruby193/lib/ruby/gems/1.9.1/gems/activerecord-3.1.3/lib/active\u record/attribute\u methods.rb:60:in
method\u missing',from config/model.rb:133:in
things',from 2stats.rb:67:in``很奇怪,列出的方法中有“things”作为方法(显然没有我的代码)。我搜索了ActiveRecord,回到了ActiveSupport的“重新定义方法”。这里的一个小输出显示方法被重新定义为:things:,而其他被重新定义的方法是:“'things=“”,我想知道这是否与覆盖别名有关。但事实是,有一个“things”方法没有我的代码,那么为什么添加:{def things super end}会失败呢!关于self.an_attribute=super | | | |“default”,我的实际代码没有默认值,而是有self.calculate_thi_和一些类似的属性sah,如何在| |语句中插入两行?我查找过,但找不到正确执行此操作的语法:
self.an_attribute=super ||{self.calculate_-simple-self.an_attribute}
(很抱歉脱离主题)
class My_class < ActiveRecord::Base
  def things
    thngs = super
    if thngs.empty? #we've got to assemble the this collection!
      self.other_things.each do |other_thing| #loop through the other things
        #analysis of the other_things and creation and addition of things
        self.things << a_thing_i_want
      end  
    else #just return them
      thngs
    end
  end
end

test = My_class.new
test.other_things << other_thing1
test.other_things << other_thing2
p test.things # => METHOD ERROR ON THE 'super' ARGH FAIL :(