ActiveRecord is an object-relational mapping (ORM) layer provided by rails, starting with the basics of active record, connecting databases, mapping tables, accessing data, and more.
Active record uses basic ORM mode: tables are mapped to classes, row mappings become objects, and columns are mapped to object properties. Unlike many of the most heavily configured ORM libraries, the Active record minimizes configuration. Imagine a program that uses an active record to convert the Orders table in the MySQL database to a class, find the order by the ID, set the name of the order, and then save it back to the database:
Require "RubyGems"
require_gem "ActiveRecord"
activerecord::base.establish_connection (: Adapter => " MySQL ",
: Host =>" localhost ",:d atabase =>" Railsdb ")
class Order < ActiveRecord::Base end
order = Order.find (123)
order.name = "Dave Thomas"
order.save
In the above example, no configuration is required, and the Active record does these things for us, so let's look at how ActiveRecord works.
Tables and Classes
When you create a subclass of a activerecord::base class, the Active record assumes that the table name is plural and the class name is singular, and when the class name includes more than one word, the table name is assumed to be an underscore between the words, and the plural form is irregular, for example:
Class Name Table name Class name order
orders LineItem line_items
taxagency tax_agencies Person people
diagnosis diagnoses Quantity quantities Batch batches Datum
Data
By default, the table name of the Active record is plural, the class name is singular, and if you are not accustomed to it, you can disable it by setting a global tag, set in the environment.rb file in the Config directory:
Activerecord::base.pluralize_table_names = False
A single plural rule can handle most situations, and for some special cases, the Active record allows us to overwrite the default generated table name, using the Set_table_name command, for example:
Class Sheep < ActiveRecord::Base
Set_table_name "Sheep" # not ' Sheeps '
end
class Order < ActiveRecord: : Base
Set_table_name "ord_rev99_x" # Wrap a legacy table ...
End