Ruby/Rails syntax
  • Index
  • chap 1
  • chap 2
  • chap 3
  • chap 4
  • Enterprise Rails - big picture
  • Nokogiri
  • ActiveRecord - 進階功能
  • pack & unpack
  • performance
  • rails engine
  • jsonb / json / hstore
  • Deploy
  • Polymorphism/Polymorphic Associations
  • relationship
  • rvm / ENV
  • Auth
  • DB related
  • TODO N+1
  • SQL view
  • module
  • api + create-react-app
  • ONE_LINE
  • Delete & destroy association
Powered by GitBook
On this page
  • struct & hash
  • save & save!
  • bang !pa
  • new & build
  • nil? & empty? & blank?
  • update & update_all & update_attribute & update_attribute
  • Scope
  • Pluck & select

Was this helpful?

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

a = "answer"
a.capitalize!    #returns "Answer"

a = "Answer"
a.capitalize!   #returns nil

a = "Answer"
a.capitalize   #returns "Answer"

new & build

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

google = Firm.new.save   # Create and save a new Firm
=> true 

google.clients         # No clients yet
=> [] 

google.clients.new     # Create a new client
 => #<Client id: nil, firm_id: 1, created_at: nil, updated_at: nil>

google.clients         # Still no clients
 => [] 

google.clients.build   # Create a new client with build
 => #<Client id: nil, firm_id: 1, created_at: nil, updated_at: nil> 

google.clients         # New client is added to clients 
 => [#<Client id: nil, firm_id: 1, created_at: nil, updated_at: nil>] 

google.save
 => true 

google.clients         # Saving firm also saves the attached client
 => [#<Client id: 1, firm_id: 1, created_at: "2011-02-11 00:18:47",
updated_at: "2011-02-11 00:18:47">]

nil? & empty? & blank?

nil? - if variable is referencing an object or not
empty? - check on types like empty string "" or empty array []
blank? - checks for nil? or empty?.

update & update_all & update_attribute & update_attribute

update(id,attributes)

  1. Update single or multiple objects

  2. invoke validation

Model.update([1,2],[{language: "ruby", framework: "rails"},{id: "jason"}])

update_all(attribute, conditions, options)

  1. multiple objects

  2. not invoke validation

Model.update_all("language = "ruby", "framework Like '%rails'", limeit: 2)

update_attribute

  1. single objects

  2. single attribute

  3. not invoke validation

obj.update_attribute(language: "php")

update_attributes

  1. single objects

  2. multiple attribute

  3. invoke validation

attributes = {name: "xyz", age: 20}
obj.update_attributes(attributes)

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.

class Shirt < ActiveRecord::Base

  scope :colored, lambda { |color| where(color: color) }

  scope :colored, ->(color) { where(color: color) }

  def self.colored(color)
    where(color: color)
  end
end

Pluck & select

pluck return array of value

select return array of model

User.select(:id).to_a

# => User Load (0.9ms)  SELECT id FROM "users"
# => [#<User id: 12>, #<User id: 42>, #<User id: 1>, #<User id: 24>, #<User id: 200>, ...]
User.pluck(:id)

# => (0.9ms)  SELECT "users"."id" FROM "users"
# => [12, 42, 1, 24, 200, ..., 365]

Reaction.where.not(rxn_center: nil).distinct.pluck(:rxn_center)
Previouschap 1Nextchap 3

Last updated 5 years ago

Was this helpful?