Module: BazaModels::Model::Queries::ClassMethods

Defined in:
lib/baza_models/model/queries.rb

Instance Method Summary collapse

Instance Method Details

#find(id) ⇒ Object



7
8
9
10
11
# File 'lib/baza_models/model/queries.rb', line 7

def find(id)
  row = db.select(table_name, {id: id}, limit: 1).fetch
  raise BazaModels::Errors::RecordNotFound, "Record not found by ID: #{id}" unless row
  new(row, init: true)
end

#find_by(where_hash) ⇒ Object



13
14
15
# File 'lib/baza_models/model/queries.rb', line 13

def find_by(where_hash)
  where(where_hash).first
end

#find_by!(where_hash) ⇒ Object



17
18
19
20
21
# File 'lib/baza_models/model/queries.rb', line 17

def find_by!(where_hash)
  model = find_by(where_hash)
  return model if model
  raise BazaModels::Errors::RecordNotFound, "Record not found by arguments: #{where_hash}" unless model
end

#find_or_create_by(data) {|model| ... } ⇒ Object

Yields:

  • (model)


29
30
31
32
33
34
# File 'lib/baza_models/model/queries.rb', line 29

def find_or_create_by(data)
  model = find_or_initialize_by(data)
  model.save if model.new_record?
  yield model if block_given?
  model
end

#find_or_create_by!(data) {|model| ... } ⇒ Object

Yields:

  • (model)


36
37
38
39
40
41
# File 'lib/baza_models/model/queries.rb', line 36

def find_or_create_by!(data)
  model = find_or_initialize_by(data)
  model.save! if model.new_record?
  yield model if block_given?
  model
end

#find_or_initialize_by(data) ⇒ Object



23
24
25
26
27
# File 'lib/baza_models/model/queries.rb', line 23

def find_or_initialize_by(data)
  model = find_by(data)
  return model if model
  new(data)
end