Note that there are some explanatory texts on larger screens.

plurals
  1. POModules vs. Classes and their influence on descendants of ActiveRecord::Base
    primarykey
    data
    text
    <p>Here's a Ruby OO head scratcher for ya, brought about by this Rails scenario: </p> <pre><code>class Product &lt; ActiveRecord::Base has_many(:prices) # define private helper methods end module PrintProduct attr_accessor(:isbn) # override methods in ActiveRecord::Base end class Book &lt; Product include PrintProduct end </code></pre> <p><code>Product</code> is the base class of all products. Books are kept in the <code>products</code> table via STI. The <code>PrintProduct</code> module brings some common behavior and state to descendants of <code>Product</code>. <code>Book</code> is used inside <code>fields_for</code> blocks in views. This works for me, but I found some odd behavior:</p> <ul> <li>After form submission, inside my controller, if I call a method on a book that is defined in <code>PrintProduct</code>, and that method calls a helper method defined in <code>Product</code>, which in turn calls the <code>prices</code> method defined by <code>has_many</code>, I'll get an error complaining that <code>Book#prices</code> is not found.</li> </ul> <p>Why is that? Book is a direct descendant of Product! </p> <p>More interesting is the following..</p> <p>As I developed this hierarchy <code>PrintProduct</code> started to become more of an abstract <code>ActiveRecord::Base</code>, so I thought it prudent to redefine everything as such:</p> <pre><code>class Product &lt; ActiveRecord::Base end class PrintProduct &lt; Product end class Book &lt; PrintProduct end </code></pre> <p>All method definitions, etc. are the same. In this case, however, my web form won't load because the attributes defined by <code>attr_accessor</code> (which are "virtual attributes" referenced by the form but not persisted in the DB) aren't found. I'll get an error saying that there is no method <code>Book#isbn</code>. Why is that?? I can't see a reason why the <code>attr_accessor</code> attributes are not found inside my form's <code>fields_for</code> block when <code>PrintProduct</code> is a class, but they are found when <code>PrintProduct</code> is a <code>Module</code>. </p> <p>Any insight would be appreciated. I'm dying to know why these errors are occurring! </p>
    singulars
    1. This table or related slice is empty.
    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