覆盖ActiveRecord集合(关联)方法

时间:2012-01-08 16:38:17

标签: 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:
      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_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 :(

不幸的是,这失败了。任何解决方案的想法?我不认为扩展是正确的解决方案


到目前为止尝试:

super - &gt; 'method_missing': super: no superclass method

self[:things] - &gt; test.things.each生成nilClass错误

潜在的解决方案:

thingspriv_things的表列和has_many关联重命名。这样我就可以简单地创建things方法并使用self.priv_things代替super

0 个答案:

没有答案