xdotcommer
xdotcommer

Reputation: 793

Rails 4 STI inheritance column not getting set

I have used STI in the past without a problem, but have had this issue on Rails 4 (4.0.5 and 4.1.4) when trying to use a custom inheritance column. The problem is that the column does not get set automatically.

Given:

class Place < ActiveRecord::Base
    self.abstract_class = true
    self.inheritance_column = :category
end

class City < Place
    self.table_name = 'places'
end

City.create location: 'Baltimore'

The category doesn't get set, but I can set it manually with

City.create location: 'Baltimore', category: 'City'

I'm not sure what the issue is. The Places model has only the location (string) and category (string) columns.

Thanks for any help

Upvotes: 1

Views: 295

Answers (1)

sandre89
sandre89

Reputation: 5898

I struggled for a few minutes with this as well. The problem is the self.abstract_class = true.

When you set that to true, that class disappears from the inheritance chain for the STI, and Rails can't discover the table name correctly.

But how to proceed if your base class - like mine - is an abstract class, one that you don't want persisted to your database?

Simple: add a validates :type, presence: true in your base class, and also make your type column null: false on your migration.

This answer came from the official Rails docs, here:


# Consider the following default behaviour:

Shape = Class.new(ActiveRecord::Base)
Polygon = Class.new(Shape)
Square = Class.new(Polygon)

Shape.table_name   # => "shapes"
Polygon.table_name # => "shapes"
Square.table_name  # => "shapes"
Shape.create!      # => #<Shape id: 1, type: nil>
Polygon.create!    # => #<Polygon id: 2, type: "Polygon">
Square.create!     # => #<Square id: 3, type: "Square">

# However, when using abstract_class, Shape is omitted from the hierarchy:

class Shape < ActiveRecord::Base
  self.abstract_class = true
end
Polygon = Class.new(Shape)
Square = Class.new(Polygon)

Shape.table_name   # => nil
Polygon.table_name # => "polygons"
Square.table_name  # => "polygons"
Shape.create!      # => NotImplementedError: Shape is an abstract class and cannot be instantiated.
Polygon.create!    # => #<Polygon id: 1, type: nil>
Square.create!     # => #<Square id: 2, type: "Square">

Then it finally states:

Note that in the above example, to disallow the creation of a plain Polygon, you should use validates :type, presence: true, instead of setting it as an abstract class. This way, Polygon will stay in the hierarchy, and Active Record will continue to correctly derive the table name.

Like I said, I'm also adding the null: false to the type column in my migration. That way I'm sure my base class will never be persisted to the database.

Upvotes: 0

Related Questions