1. When you create an ActiveRecord:: Base subclass, are in fact the packaging of a database table.
2.active record the assumption that table name is the plural form of categories. If the class name contains more than one in capital letters at the beginning of the word, table name will be assumed that the separation of these underlined words.
3. If you do not like the above practices, you can: in the configuration file to set up a global variable turn off it, in the config directory environment.rb file settings.
ActiveRecord::Base.pluralize_table_names=false
4. Connect to database
active record put the concept of an abstract database connection out to help deal with various special procedures of the underlying details of database. active record procedures for use of a common call, a group of agent the details of the database adapter.
Specify a way to connect is to use establish_connection () class method.
For example,
ActiveRecord::Base.establish_connection( :adapter => "mysql", :host => "dbserver.com", :database => "railsdb", :username => "railsuser", :password => "railspw" )
The second approach is: We can also at config / database.yml configuration file to set up connection parameters.
The benefits of doing so is not only to connect information and code separation, but also conducive to testing and deployment.
5. To create a new record
We can call Order.new () to create an object that the orders table rows. Then fill the property's value, the corresponding table columns. Finally the object call save () method to the database storage.
active record of the constructor can have an optional parameter block. If used, then the block will be called as a parameter to create an Order. Such usage has the advantage, you can not create a temporary variable.
Order.new do |o| o.name = "Dave Thomas" # . . . o.save end
6. Read lines that already exist
an_order = Order.find(27) order_list = params[: order_ids] orders = Order.find(order_list) count = orders.size
find () in the back has variable refers to the first line of matching conditions, and: all of the return match the line array.
pos = Order.find(:all, :conditions => "name = 'dave' and pay_type = 'po'")
This meaning is: back in line with the name for dave, pay_type all records for the po.
pos = Order.find(:all,:conditions => "name = '#{name}' and pay_type = 'po'") This can be used directly in the variable conditions, but this easily lead to sql injection attacks.
In order to prevent sql injection attacks, we can use dynamic sql, as follows:
pos = Order.find(:all,:conditions => ["name = ? and pay_type = 'po'", name]) name = params[:name]
Or as follows:
pay_type = params[:pay_type]
name = params[:name]
pos = Order.find(:all,:conditions => ["name = :name and pay_type = :pay_type", {:pay_type => pay_type, :name => name}])
There are sort and limit
find(:all, : order => "id", :limit => page_size, : offset => page_num*page_size)
join the use of
find(:all, :conditions => "pr.title = 'Programming Ruby'", :joins => "as li inner join products as pr on li.product_id = pr.id")
find_by_sql () to bring conditions, introduction of an array, the first element is a string that contains placeholders. The remaining part of the array or a hash or a list of alternative values.
7. Give the record count
c1 = Order.count
c2 = Order.count(["name = ?", "Dave Thomas"])
c3 = LineItem.count_by_sql("select count(*) " + " from line_items, orders " + " where line_items.order_id = orders.id " + " and orders.name = 'Dave Thomas' ") puts "Dave has #{c3} line items in #{c2} orders (#{c1} orders in all)" 8. Dynamic finder
order = Order.find_by_name("Dave Thomas")
orders = Order.find_all_by_name("Dave Thomas")
order = Order.find_all_by_email(params['email'])
user = User.find_by_name_and_password(name, pw) This time for the majority to be effective, unless you have the listing such as tax_and_shipping
reload () is basically used in the unit test, and other rarely used
9. Update existing records
In addition to save () outside, active record can also let you directly use a single method call update_attribute () to change the property values and preserve the object model.
order.update_attributes(:name => "Barney", :email => "barney@bedrock.com")
order = Order.update(12, :name => "Barney", :email => "barney@bedrock.com")
result = Product.update_all("price = 1.1*price", "title like '%Java%'") 10.save () and save! () Method
If the model is effective and then be able to save, save () return true.
If you want to preserve in place the necessary model objects, all want to deal with errors automatically, you directly use the save! () It. This method should not save if the object encountered, he put forward a RecordInvalid abnormal.
begin order.save! rescue RecordInvalid => error # validation failed end
11. Delete Record
It has two types of method delete () and delete_all (), are up in the database operation level. delete () method uses an array of id or an id to delete the corresponding table records. delete_all () delete the given conditions of matching rows, if there is no condition on the delete all the records.
12. Form the relationship between
active record to support the relationship between three tables:
One-on-one, one-to-many, many-to-many. You can add a statement in the model in has_one, has_many, belongs_to, has_and_belongs_to_many
statement has_one a given category is category itself. has_one statements and belongs_to methods, like the definition of the same set, change the default behavior of active record. Except we belongs_to () see: class_name,: foreign_key,: conditions, can also use: dependent and: order. : dependent option is the son of table rows can not be independent of the corresponding parent table rows and a separate existence. This means that if you delete the parent record, and you defined: dependent => true, then, active record will automatically delete the relevant sub-table rows. : Order option, is to decide how to sort records back before.
has_many statements has_many definition of a property, it is like the same sub-class collection. Sub-table with the belongs_to to indicate its parent class. You should sub-class as an array to store, query a special sub-class, add new sub-class.
Many-to-many relationship between the many-to-many relationships are symmetrical relationship between the two tables are connected to each other using statements has_and_belongs_to_many to the relationship between them







