chap 2
struct & hash
struct & hashStruct: 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] # => 4save & save!
save & save!save!: Raise the error when exception, like validation.
save: return true or false.
bang !pa
raise exception
mutate object
In transactions, you must use bang!
With !
return the mutated object when modifications were made.
return nil when no modifications.
Without !
return a copy of the object no matter it was modified
new & build
new & buildcreating an object through an association, build should be preferred over new.
nil? & empty? & blank?
nil? & empty? & blank?
update & update_all & update_attribute & update_attribute
update & update_all & update_attribute & update_attributeupdate(id,attributes)
Update single or multiple objects
invoke validation
update_all(attribute, conditions, options)
multiple objects
not invoke validation
update_attribute
single objects
single attribute
not invoke validation
update_attributes
single objects
multiple attribute
invoke validation
Scope
ScopeNote 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 & selectpluck return array of value
select return array of model
Last updated
Was this helpful?