未验证 提交 d004f0ac 编写于 作者: R Ryuta Kamizono 提交者: GitHub

Merge pull request #31171 from sambostock/improve-abstract-class-documentation

Expand AR::Base.abstract_class documentation

[ci skip]
...@@ -104,21 +104,47 @@ def base_class ...@@ -104,21 +104,47 @@ def base_class
end end
end end
# Set this to true if this is an abstract class (see <tt>abstract_class?</tt>). # Set this to +true+ if this is an abstract class (see
# If you are using inheritance with ActiveRecord and don't want child classes # <tt>abstract_class?</tt>).
# to utilize the implied STI table name of the parent class, this will need to be true. # If you are using inheritance with Active Record and don't want a class
# For example, given the following: # to be considered as part of the STI hierarchy, you must set this to
# true.
# +ApplicationRecord+, for example, is generated as an abstract class.
# #
# class SuperClass < ActiveRecord::Base # 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 <tt>abstract_class</tt>, +Shape+ is omitted from
# the hierarchy:
#
# class Shape < ActiveRecord::Base
# self.abstract_class = true # self.abstract_class = true
# end # end
# class Child < SuperClass # Polygon = Class.new(Shape)
# self.table_name = 'the_table_i_really_want' # Square = Class.new(Polygon)
# end
#
# #
# <tt>self.abstract_class = true</tt> is required to make <tt>Child<.find,.create, or any Arel method></tt> use <tt>the_table_i_really_want</tt> instead of a table called <tt>super_classes</tt> # 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">
# #
# Note that in the above example, to disallow the creation of a plain
# +Polygon+, you should use <tt>validates :type, presence: true</tt>,
# 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.
attr_accessor :abstract_class attr_accessor :abstract_class
# Returns whether this class is an abstract class or not. # Returns whether this class is an abstract class or not.
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册