diff --git a/rails-models.md b/rails-models.md index 484c45b09..cfa95e019 100644 --- a/rails-models.md +++ b/rails-models.md @@ -3,7 +3,7 @@ title: Models category: Rails --- -### [Query methods](http://devdocs.io/rails/activerecord/querymethods#method-i-order) +### [QueryMethods](http://devdocs.io/rails/activerecord/querymethods) ```rb items = Model @@ -78,9 +78,6 @@ item.update_columns! name: "John" item.touch # updates :updated_at item.touch :published_at -item.valid? -item.invalid? - item.destroy item.delete # skips callbacks ``` @@ -90,8 +87,50 @@ Model.create # Same an #new then #save 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 ----------