Active record makes it easy to implement CRUD database basics, in the following sections we use the Orders table in the MySQL database for CRUD operations, this time we look at the creation.
We're supposed to have a model called Order:
Class Order < ActiveRecord::Base end
In the object-oriented model, the table corresponds to the class, and the row in the table corresponds to the object of the class. We can create a record by creating an object for a class. For the Orders table, we can use the Order.new () method to create an order object, which corresponds to a record of the Orders table, and then we assign a value to each property of the object, and finally, we call the object's Save () method to write the data back to the database. If you do not call Save (), the object exists only in memory, not the database.
An_order = order.new
an_order.name = "Dave Thomas"
an_order.email = "dave@pragprog.com"
an_order.address = "123 Main St"
an_order.pay_type = "Check"
an_order.save
The constructor for an Active record has an optional block, which can be used as a parameter to create an order object so that there is no need to create a variable for the object of the Order class:
Order.new do |o|
O.name = "Dave Thomas"
#
... O.save End
An Active record can also receive the value of a set of hash parameters as an optional parameter, consisting of the name of the attribute and the corresponding value:
An_order = order.new (
: Name => "Dave Thomas"
: Email => "dave@pragprog.com": Address
=> "
123 Main St
",
:p ay_type =>" Check ")
An_order.save