Ruby on Rails development from scratch (44)-ActiveRecord Foundation (record creation)

Source: Internet
Author: User
Tags mysql database ruby on rails

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.