rails-models: more tricks
This commit is contained in:
parent
c99ca41992
commit
3233a07ea6
|
@ -3,7 +3,7 @@ title: Models
|
||||||
category: Rails
|
category: Rails
|
||||||
---
|
---
|
||||||
|
|
||||||
### [Query methods](http://devdocs.io/rails/activerecord/querymethods#method-i-order)
|
### [QueryMethods](http://devdocs.io/rails/activerecord/querymethods)
|
||||||
|
|
||||||
```rb
|
```rb
|
||||||
items = Model
|
items = Model
|
||||||
|
@ -78,9 +78,6 @@ item.update_columns! name: "John"
|
||||||
item.touch # updates :updated_at
|
item.touch # updates :updated_at
|
||||||
item.touch :published_at
|
item.touch :published_at
|
||||||
|
|
||||||
item.valid?
|
|
||||||
item.invalid?
|
|
||||||
|
|
||||||
item.destroy
|
item.destroy
|
||||||
item.delete # skips callbacks
|
item.delete # skips callbacks
|
||||||
```
|
```
|
||||||
|
@ -90,8 +87,50 @@ Model.create # Same an #new then #save
|
||||||
Model.create! # Same as above, but raises an Exception
|
Model.create! # Same as above, but raises an Exception
|
||||||
```
|
```
|
||||||
|
|
||||||
### Sorting
|
### [Dirty](http://devdocs.io/rails/activerecord/dirty)
|
||||||
|
|
||||||
|
```rb
|
||||||
|
item.changed?
|
||||||
|
item.changed # ['name']
|
||||||
|
item.changed_attributes # { 'name' => 'Bob' } - original values
|
||||||
|
item.changes # { 'name' => ['Bob', 'Robert'] }
|
||||||
|
item.previous_changes # available after #save
|
||||||
|
item.restore_attributes
|
||||||
|
|
||||||
|
item.name = 'Robert'
|
||||||
|
item.name_was # 'Bob'
|
||||||
|
item.name_change # [ 'Bob', 'Robert' ]
|
||||||
|
item.name_changed? # true
|
||||||
|
item.name_changed?(from: 'Bob', to: 'Robert')
|
||||||
|
```
|
||||||
|
|
||||||
|
### [Validations](http://devdocs.io/rails/activerecord/validations)
|
||||||
|
|
||||||
|
```rb
|
||||||
|
item.valid?
|
||||||
|
item.invalid?
|
||||||
|
```
|
||||||
|
|
||||||
|
### [Calculations](http://devdocs.io/rails/activerecord/calculations)
|
||||||
|
|
||||||
|
```rb
|
||||||
|
Person.count
|
||||||
|
Person.count(:age) # counts non-nil's
|
||||||
|
|
||||||
|
Person.average(:age)
|
||||||
|
Person.maximum(:age)
|
||||||
|
Person.minimum(:age)
|
||||||
|
Person.sum('2 * age')
|
||||||
|
|
||||||
|
Person.calculate(:count, :all)
|
||||||
|
```
|
||||||
|
|
||||||
|
Advanced:
|
||||||
|
|
||||||
|
```
|
||||||
|
Person.distinct.count
|
||||||
|
Person.group(:city).count
|
||||||
|
```
|
||||||
|
|
||||||
Generating
|
Generating
|
||||||
----------
|
----------
|
||||||
|
|
Loading…
Reference in New Issue