Note that there are some explanatory texts on larger screens.

plurals
  1. POOverriding ActiveRecord collection (association) methods
    primarykey
    data
    text
    <p>I'm new to Ruby and I'm trying to create a model where collections are assembled if they do not exist.</p> <p>I already overloaded individual attributes like so:</p> <pre><code>class My_class &lt; 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 # =&gt; "default" </code></pre> <p>This works great and basically gives me ||= functionality.</p> <p>So, without thinking, I went and wrote myself a pretty big function to do the same with a collection (i.e. if there are no objects in the collection, then go and work out what they should be)</p> <pre><code>class My_class &lt; 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 &lt;&lt; a_thing_i_want end else #just return them thngs end end end test = My_class.new test.other_things &lt;&lt; other_thing1 test.other_things &lt;&lt; other_thing2 p test.things # =&gt; METHOD ERROR ON THE 'super' ARGH FAIL :( </code></pre> <p>This fails unfortunately. Any ideas for solutions? I don't <em>think</em> extensions are the right solution here</p> <hr> <p>Attempted so far:</p> <p><code>super</code> --> <code>'method_missing': super: no superclass method</code></p> <p><code>self[:things]</code> --> <code>test.things.each</code> generates a nilClass error</p> <p>Potential solution:</p> <p>Would be rename the table column and has_many association from <code>things</code> to <code>priv_things</code>. This would allow me to simply create the <code>things</code> method and use <code>self.priv_things</code> instead of <code>super</code></p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload