chap 2

struct & hash

Struct: to bundle attributes together, using accessor methods, without writing an explicit class. Like old C++ plus.

Hash a collection of key-value pairs.

Point = Struct.new(:x, :y) # use struct to create a class.
p = Point.new(4,5) # => #<struct Point x=4, y=5> 
p.x # => 4 
p.y # => 5 

q = {x: 4, y: 5}
q.x # NoMethodError: undefined method `x'
q[:x] # => 4

save & save!

save!: Raise the error when exception, like validation. save: return true or false.

bang !pa

  1. raise exception

  2. mutate object

In transactions, you must use bang!

With !

  1. return the mutated object when modifications were made.

  2. return nil when no modifications.

Without !

return a copy of the object no matter it was modified

new & build

creating an object through an association, build should be preferred over new.

nil? & empty? & blank?

update & update_all & update_attribute & update_attribute

update(id,attributes)

  1. Update single or multiple objects

  2. invoke validation

update_all(attribute, conditions, options)

  1. multiple objects

  2. not invoke validation

update_attribute

  1. single objects

  2. single attribute

  3. not invoke validation

update_attributes

  1. single objects

  2. multiple attribute

  3. invoke validation

Scope

Note that scope is simply syntactic sugar for defining an actual class query method:

Scoping = method calls on the association objects or models.(where, joins and includes). It will return an ActiveRecord::Relation object which allow for further methods to be called on it.

the following 3 items are the same.

Pluck & select

pluck return array of value

select return array of model

Last updated

Was this helpful?