Ruby on Rails development from scratch (38)-ActiveRecord Basics (columns and attributes)

Source: Internet
Author: User
Tags require ruby on rails

One of the objects in the ActiveRecord corresponds to a row of tables in the database, and the object's properties correspond to the columns of the table, and you may notice that our order class does not mention anything about the Orders table because ActiveRecord determines these relationships at runtime. An Active record reacts a pattern in a database to a class.

Our Orders table may be created using the following SQL:

CREATE TABLE orders (
ID int not NULL auto_increment,
name varchar (MB) NOT NULL,
email varchar (255) NOT NULL, Address
text is not NULL,
Pay_type char (a) not NULL,
shipped_at datetime null,
primary key (ID)
);

We can create a class to convert this table:

Require ' RubyGems '
require_gem ' ActiveRecord '
Connection code omitted ...
Class Order < ActiveRecord::Base end

When we create an order class, we can access its properties to get information, and the following code uses the columns () method to return an array of columns objects, where we display each column in the Orders table and display the details of the specified field.

Require ' PP ' pp
Order.columns.map {|col| col.name}
pp order.columns_hash[' shipped_at ']

When you run the code, you get the following output:

["id", "name", "email", "address", "Pay_type", "Shipped_at"]
#<activerecord::connectionadapters::column:0x10e4a50
@default =nil,
@limit =nil,
@name = "Shipped_ At ",
@type =:d atetime>

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.