Ruby on Rails development from scratch (52)-ActiveRecord Basics (Delete records)

Source: Internet
Author: User
Tags ruby on rails

The Active record provides two ways to delete operations. First, there are two class-level methods, delete and Delete_all, at the database level, and the Delete () method receives one or a set of Id,delete_all () methods corresponding to the database to delete all records that meet the specified criteria, if no conditions are specified, All of the records will be deleted. The return value of the method is related to a specific database adapter, such as the number of rows affected by Oracle return. If no records are deleted, the exception is not thrown.

Order.delete (123)
user.delete ([2,3,4,5])
product.delete_all (["Price >?", @expensive_price])

In addition, the Destory method deletes the model object that corresponds to the row in the database, which freezes the objects and cannot modify the value of the object.

Order = Order.find_by_name ("Dave")
Order.destroy

There are two class-level destory methods, and the Destory () method receives one or a set of Id,destory_all () methods to receive a deletion condition. Both methods read the corresponding record to the model object from the database, and call the instance-level Destory () method on the object, and do not return meaningful information.

Order.destroy_all (["Shipped_at <?", 30.days.ago])

Why do we need the Delete and Destory methods at the same time? The Delete method bypasses some of the active record callbacks (callback) and validation functions, while using destory does not, we usually use the Destory method to ensure that our database is consistent and does not break the business logic contained in the model.

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.