How do you delete an ActiveRecord object?
How do you delete an ActiveRecord object?
I looked at Active Record Querying and it does not have anything on deleting that I can see.
Delete by id
,
Delete the current object like: user.remove
,
Can you delete based on a where
clause?
It's destroy
and destroy_all
methods, like
user.destroy
User.find(15).destroy
User.destroy(15)
User.where(age: 20).destroy_all
User.destroy_all(age: 20)
Alternatively you can use delete
and delete_all
which won't enforce :before_destroy
and :after_destroy
callbacks or any dependent association options.
User.delete_all(condition: 'value')
will allow you to delete records without a primary key
There is delete
, delete_all
, destroy
, and destroy_all
.
The docs are: older docs and Rails 3.0.0 docs
delete
doesn't instantiate the objects, while destroy
does. In general, delete
is faster than destroy
.
User.destroy
User.destroy(1)
will delete user with id == 1
and :before_destroy
and :after_destroy
callbacks occur. For example if you have associated records
has_many :addresses, :dependent => :destroy
After user is destroyed his addresses will be destroyed too. If you use delete action instead, callbacks will not occur.
User.destroy
, User.delete
User.destroy_all(<conditions>)
or User.delete_all(<conditions>)
Notice : User is a class and user is an instance object
链接地址: http://www.djcxy.com/p/49720.html上一篇: 大写名称的Rails命名约定