1

UPDATE:
changing table_name to self.table_name = seems to have convinced rails to use the correct table.

I am, however, now getting these weird errors

   Mysql2::Error: Unknown column 'templates.deleted_at' in 'where clause': SELECT `objekts`.* FROM `objekts`  WHERE (`templates`.`deleted_at` IS NULL)

ORIGINAL QUESTION:

I have a Template, and an Objekt:

class Template < ActiveRecord::Base
  def status; 0; end # Template doesn't have a status column, so define default
end

class Objekt < Template
  table_name = "objekts" # there is a status column in this table
end

but when I do, Objekt.new.attributes in the console, it only lists the attributes from the Template object, and doesn't list any of the Objekt.

Every column on the Template is also available in the Objekt, but the Objekt has an additional 10 columns (mostly flags)

what's going on here? why does rails not hook up the Objekt class to the objekts table?

NullVoxPopuli
  • 61,906
  • 73
  • 206
  • 352
  • Would a `has_many/belongs_to` relationship not be better here instead of using the Template Method Pattern? Template is more of a `base` class in this case. `Objekt` should be relatable to a table. Convention over configuration. – ChuckJHardy Jun 05 '13 at 16:47
  • Well, Template has a ton of methods that Objekt should also have. that's why I think Inheritance is the best case, here. Mayble Table-Inheritance isn't the right term at all. I want both objects to have entirely separate tables.. it just so happens that the tables share some column names. Mostly, I want to share methods between the two. A module won't work, because then it overrides Objekt's column definitions (or would). – NullVoxPopuli Jun 05 '13 at 16:53
  • 1
    I prefer to follow the pattern of `composition over inheritance`. Could you not move the methods out of template to a module and include/extend them within Objekt as required? They can then both inherit from `ActiveRecord::Base` – ChuckJHardy Jun 05 '13 at 16:55

1 Answers1

1

Ref the comments above when I refer to composition over inheritance I was thinking about something like this...

class Objekt < ActiveRecord::Base
  include Template

  def status
    self.random_column_name || super
  end
end

module Template
  def status
    0
  end
end
ChuckJHardy
  • 6,956
  • 6
  • 35
  • 39
  • It should be noted that this works if status isn't a column name. Since, for example, I have random_column_name as a column, I ended up just defining that in my "Super class" and didn't define it in the module. So, what I learned: Modules can be used for shared methods between two active record models such that those methods are not columns in one of the models. – NullVoxPopuli Jun 05 '13 at 19:40
  • Good to hear. Thanks for the tick :) – ChuckJHardy Jun 05 '13 at 19:42