Class: Cybertrain::Model
- Inherits:
-
Object
- Object
- Cybertrain::Model
- Defined in:
- cybertrain/model.rb,
cybertrain/model/bulk_writes.rb
Overview
Base class of every model.
You never subclass it by hand: spin run gen writes one subclass per table
in db/schema.rb into gen/models/<singular>.rb (attribute accessors,
casts, finders and the associations read off foreign keys; see Article
for the full generated surface), and app/models/<singular>.rb reopens it,
with no superclass, for validations, callbacks and your own methods:
# app/models/article.rb
class Article
validates :title, presence: true
validates :body, presence: true, length: { minimum: 10 }
before_save { |article| article.title = article.title.strip }
def summary = body[0, 80]
end
Re-run spin run gen after changing the schema (cybertrain db migrate
and the development server do it for you).
Associations come from the schema’s foreign keys and from Model.has_many / Model.has_one / Model.belongs_to lines in the app/models file.
Not available (compared with ActiveRecord): polymorphic associations,
has_many :through, nested includes, eager_load and joins,
select, a one-column pluck (relations have pluck_str /
pluck_int / pluck_float; pluck takes two or more columns), a
polymorphic sum / minimum / maximum (they come typed: sum_int,
minimum_time, …), a where over a Range with other than Integer
ends (use where_between), deterministic encryption, dirty tracking,
transactions around save (except a counter_cache child’s update),
STI and enums.
Implementation: validations and callbacks are runtime data keyed by model name, since Spinel cannot define methods at runtime.
Instance Attribute Summary collapse
-
#id ⇒ Integer
readonly
The primary key,
0until the record is first saved.
Class Method Summary collapse
-
.after_create {|record| ... } ⇒ nil
Runs in #save of a new record, after the INSERT (the record has its id).
-
.after_destroy {|record| ... } ⇒ nil
Runs in #destroy after the DELETE.
-
.after_save {|record| ... } ⇒ nil
Runs in #save after the row is written and after
after_create/after_update. -
.after_update {|record| ... } ⇒ nil
Runs in #save of a persisted record, after the UPDATE.
-
.before_create {|record| ... } ⇒ nil
Runs in #save of a new record, after
before_save, before the INSERT. -
.before_destroy {|record| ... } ⇒ nil
Runs in #destroy before the
dependent:children go and before the DELETE, inside destroy’s transaction. -
.before_save {|record| ... } ⇒ nil
Runs in #save after validation passes, before the INSERT or UPDATE.
-
.before_update {|record| ... } ⇒ nil
Runs in #save of a persisted record, after
before_save, before the UPDATE. - .before_validation {|record| ... } ⇒ nil
-
.belongs_to(name, class_name: nil, foreign_key: nil, optional: false, counter_cache: false) ⇒ nil
Declares the parent a record points to:
belongs_to :authorreadsAuthor.find_by(id: author_id)and keeps it untilauthor_idchanges or #reload. -
.encrypts(*attrs) ⇒ nil
Encrypts columns at rest:
encrypts :api_key, :notes(spec section 10). -
.has_many(name, dependent: nil, class_name: nil, foreign_key: nil) ⇒ nil
Declares that each record has many children:
has_many :commentsreads the comments whose<singular of this table>_idis this record’s id. -
.has_one(name, dependent: nil, class_name: nil, foreign_key: nil) ⇒ nil
Declares that each record has at most one child:
has_one :profilereadsProfile.find_by(user_id: id)(nil when there is none). -
.model_concern_insert_at(validators_index) ⇒ nil
Written by gen/concerns.rb (
spin run gen) around theincludedbody of a model concern it splices into this class (spec 4.2): until Model.model_concern_insert_done, the rules itsvalidatescalls declare go before the model’s own call numbervalidators_index(the count of the model’svalidatescalls above theincludeline), not to the end, so they run where theincludewas written. -
.model_concern_insert_done ⇒ nil
Ends a Model.model_concern_insert_at splice:
validatesappends again. -
.scope(name, body) ⇒ nil
Declares a named query:
scope :recent, -> { order(created_at: :desc) }or, with parameters,scope :min_views, ->(n) { where("views >= ?", n) }. -
.transaction(immediate: false) {|conn| ... } ⇒ nil
Cybertrain::DB.transaction, under the name Rails gives it: saves, updates, destroys and queries run in the block (on this thread) are one transaction, committed when the block returns and rolled back when it raises. -
.upsert(attrs, conflict:, update: {}) ⇒ Integer
Inserts one row, or, when it collides with an existing row on the
conflictcolumns (a UNIQUE index or the primary key), updates that row instead: SQLite’s `INSERT … -
.validate(*args) ⇒ nil
Declares methods that validate the record by adding to #errors themselves, run by #valid? after the Model.validates rules:
validate :check_dates, :check_totals, on: :update, if: :published?, unless: :imported?. - .validates(*args) ⇒ nil
-
.validates_foreign_key(attr) ⇒ nil
The validation a declared Model.belongs_to adds to its generated class: “can’t be blank” on the foreign key while it is nil, blank or 0 (the id of no saved record), so
savereturns false instead of the database refusing the row.
Instance Method Summary collapse
-
#==(other) ⇒ Boolean
Records are equal when they are the same model and the same saved row.
-
#as_json ⇒ Hash{String => Object}
#attributes, ready for JSON: a Time becomes its ISO 8601 String (
"2026-10-05T09:00:00.000Z"); booleans, numbers, Strings and nil stay as they are (Cast.to_sql would turn booleans into 1/0). -
#attributes ⇒ Hash{String => Object}
Every column, keyed by its SQL name,
"id"first, with typed values. -
#destroy ⇒ Boolean
Runs Model.before_destroy, removes the
dependent:children of Model.has_many / Model.has_one, deletes the row, runs Model.after_destroy, all in one transaction (joining one already open): a raise anywhere rolls every step back and the record stays #persisted?. - #errors ⇒ Errors
-
#new_record? ⇒ Boolean
The opposite of #persisted?.
-
#persisted? ⇒ Boolean
True once the record has been saved or was loaded from the database, false after #destroy.
-
#reload ⇒ self
Re-reads every column from the database and forgets every association it had read (a belongs_to parent, a preload).
-
#save ⇒ Boolean
Validates, then runs before_save, before_create/before_update, writes the row, and runs after_create/after_update and after_save – the ActiveRecord order.
-
#save! ⇒ true
Like #save, but raises instead of returning false.
-
#to_json ⇒ String
#as_json as a JSON String, e.g.
-
#to_param ⇒ String
The id as a String, what route helpers put in a URL (
"0"for a new record). -
#update(attrs) ⇒ Boolean
Assigns the attributes (cast to the column types, unknown keys ignored) and saves.
-
#update_columns(attrs) ⇒ true
Writes the given columns straight to the row with one UPDATE of exactly those columns, then keeps the new values on the record: no validation, no callback,
updated_atleft alone. -
#valid? ⇒ Boolean
Clears #errors, runs the Model.before_validation callbacks, then every rule declared with Model.validates, then the Model.validate methods.
Instance Attribute Details
#id ⇒ Integer (readonly)
The primary key, 0 until the record is first saved.
505 506 507 |
# File 'cybertrain/model.rb', line 505 def id @id end |
Class Method Details
.after_create {|record| ... } ⇒ nil
Runs in #save of a new record, after the INSERT (the record has its id).
372 373 374 375 376 377 |
# File 'cybertrain/model.rb', line 372 def self.after_create(&block) = add_model_callback("after_create", block) # Runs in {#save} of a persisted record, after `before_save`, before the # UPDATE. # @yieldparam record [Model] # @return [nil] # @api public |
.after_destroy {|record| ... } ⇒ nil
Runs in #destroy after the DELETE.
396 |
# File 'cybertrain/model.rb', line 396 def self.after_destroy(&block) = add_model_callback("after_destroy", block) |
.after_save {|record| ... } ⇒ nil
Runs in #save after the row is written and after after_create /
after_update.
362 363 364 365 366 |
# File 'cybertrain/model.rb', line 362 def self.after_save(&block) = add_model_callback("after_save", block) # Runs in {#save} of a new record, after `before_save`, before the INSERT. # @yieldparam record [Model] # @return [nil] # @api public |
.after_update {|record| ... } ⇒ nil
Runs in #save of a persisted record, after the UPDATE.
383 384 385 386 387 388 389 390 |
# File 'cybertrain/model.rb', line 383 def self.after_update(&block) = add_model_callback("after_update", block) # Runs in {#destroy} before the `dependent:` children go and before the # DELETE, inside destroy's transaction. # @example # before_destroy { |article| AuditLog.create(note: "deleted #{article.id}") } # @yieldparam record [Model] # @return [nil] # @api public |
.before_create {|record| ... } ⇒ nil
Runs in #save of a new record, after before_save, before the INSERT.
367 368 369 370 371 |
# File 'cybertrain/model.rb', line 367 def self.before_create(&block) = add_model_callback("before_create", block) # Runs in {#save} of a new record, after the INSERT (the record has its id). # @yieldparam record [Model] # @return [nil] # @api public |
.before_destroy {|record| ... } ⇒ nil
Runs in #destroy before the dependent: children go and before the
DELETE, inside destroy’s transaction.
391 392 393 394 395 |
# File 'cybertrain/model.rb', line 391 def self.before_destroy(&block) = add_model_callback("before_destroy", block) # Runs in {#destroy} after the DELETE. # @yieldparam record [Model] # @return [nil] # @api public |
.before_save {|record| ... } ⇒ nil
Runs in #save after validation passes, before the INSERT or UPDATE.
356 357 358 359 360 361 |
# File 'cybertrain/model.rb', line 356 def self.before_save(&block) = add_model_callback("before_save", block) # Runs in {#save} after the row is written and after `after_create` / # `after_update`. # @yieldparam record [Model] # @return [nil] # @api public |
.before_update {|record| ... } ⇒ nil
Runs in #save of a persisted record, after before_save, before the
UPDATE.
378 379 380 381 382 |
# File 'cybertrain/model.rb', line 378 def self.before_update(&block) = add_model_callback("before_update", block) # Runs in {#save} of a persisted record, after the UPDATE. # @yieldparam record [Model] # @return [nil] # @api public |
.before_validation {|record| ... } ⇒ nil
351 352 353 354 355 |
# File 'cybertrain/model.rb', line 351 def self.before_validation(&block) = add_model_callback("before_validation", block) # Runs in {#save} after validation passes, before the INSERT or UPDATE. # @yieldparam record [Model] # @return [nil] # @api public |
.belongs_to(name, class_name: nil, foreign_key: nil, optional: false, counter_cache: false) ⇒ nil
Declares the parent a record points to: belongs_to :author reads
Author.find_by(id: author_id) and keeps it until author_id
changes or #reload. Read as text by the generator, like has_many:
alone on its line, literal options only (a trailing comment is
refused).
Unless optional: true, the record is invalid while the key is nil
or 0 (“can’t be blank” on author_id; validates_foreign_key).
counter_cache: true keeps the parent’s <children>_count column
(posts.comments_count, or <has_many name>_count when the parent
declares one over this key) in step: +1 after create, -1 after
destroy (from the key the row holds, read inside destroy’s
transaction), and a move to another parent counted on both sides; the
update and both counts run in one transaction. The column must exist;
the parent’s own #save leaves it alone (its copy may be stale).
314 |
# File 'cybertrain/model.rb', line 314 def self.belongs_to(name, class_name: nil, foreign_key: nil, optional: false, counter_cache: false) = nil |
.encrypts(*attrs) ⇒ nil
Encrypts columns at rest: encrypts :api_key, :notes (spec section
10). The generator reads the line as text: the generated load_row
decrypts each column (Crypto.decrypt) and to_row encrypts it with a
fresh nonce, so the record holds the text and the table the payload
("1:...", AES-256-GCM). Each must be a string or text column, named
with Symbols, no options (there is no deterministic encryption). The
application then needs CYBERTRAIN_ENCRYPTION_KEY (boot fails
without it); the encryption is cybertrain/encryptor.rb’s (openssl),
which every program loads. where, where_like, where_between,
update_all and the bulk writes refuse an encrypted column
(ArgumentError); pluck answers the stored payload. At run time this
method does nothing; it exists so the model file loads.
211 |
# File 'cybertrain/model.rb', line 211 def self.encrypts(*attrs) = nil |
.has_many(name, dependent: nil, class_name: nil, foreign_key: nil) ⇒ nil
Declares that each record has many children: has_many :comments
reads the comments whose <singular of this table>_id is this
record’s id. Like scope, the generator reads the line as text and
writes the reader into gen/models (def comments =
CommentRelation.new("comments").where(post_id: @id)); at run time this
method does nothing. The reader returns the children’s Relation, so it
chains: post.comments.where(approved: true).count; add .to_a for
an Array. A schema foreign key gives the same reader without a
declaration; a declaration names it, or adds dependent:.
The macro is alone on its line, at class level, with literal options
only (a trailing comment, a ; or a parenthesised call stops the
generator): class_name: (a String or Symbol;
inferred from the name, comments -> Comment), foreign_key: (the
children’s column; inferred post_id) and dependent: – :destroy
(each child is loaded and destroyed, so its callbacks and its own
dependent: run), :delete_all (one DELETE) or :nullify (one
UPDATE setting the key to NULL; the column must be nullable), applied
by #destroy before its DELETE in the same transaction. Without
dependent: the database’s foreign key decides (on_delete: in the
schema). A model, column or option that does not exist stops the
generator with the file and line. No :through, scope lambda,
inverse_of or counter_cache: (that goes on the belongs_to).
268 |
# File 'cybertrain/model.rb', line 268 def self.has_many(name, dependent: nil, class_name: nil, foreign_key: nil) = nil |
.has_one(name, dependent: nil, class_name: nil, foreign_key: nil) ⇒ nil
Declares that each record has at most one child: has_one :profile
reads Profile.find_by(user_id: id) (nil when there is none). Read as
text by the generator, like has_many: alone on its line, literal
options only (a trailing comment is refused), the same options; a
has_one on a foreign key replaces the has_many the key would give.
285 |
# File 'cybertrain/model.rb', line 285 def self.has_one(name, dependent: nil, class_name: nil, foreign_key: nil) = nil |
.model_concern_insert_at(validators_index) ⇒ nil
Written by gen/concerns.rb (spin run gen) around the included
body of a model concern it splices into this class (spec 4.2):
until model_concern_insert_done, the rules its validates calls
declare go before the model’s own call number validators_index
(the count of the model’s validates calls above the include
line), not to the end, so they run where the include was written.
Not for application code.
157 158 159 160 161 162 |
# File 'cybertrain/model.rb', line 157 def self.model_concern_insert_at(validators_index) list = (VALIDATORS[self.name] ||= Array.new(0) { Validator.new(:base, :presence) }) starts = (VALIDATES_STARTS[self.name] ||= Array.new(0) { 0 }) MODEL_CONCERN_AT[self.name] = validators_index < starts.size ? starts[validators_index] : list.size nil end |
.model_concern_insert_done ⇒ nil
Ends a model_concern_insert_at splice: validates appends again.
167 168 169 170 |
# File 'cybertrain/model.rb', line 167 def self.model_concern_insert_done MODEL_CONCERN_AT.delete(self.name) nil end |
.scope(name, body) ⇒ nil
Declares a named query: scope :recent, -> { order(created_at: :desc) }
or, with parameters, scope :min_views, ->(n) { where("views >= ?", n) }.
The generator reads the line as text (nothing is evaluated): it copies
the lambda’s parameters and body into a method of the model’s Relation
(def min_views(n) = where("views >= ?", n), so the body runs on the
relation) and a class method (def self.min_views(n) = all.min_views(n)),
so Post.recent.min_views(2).first chains like any other query. At run
time this method does nothing; it exists so the model file loads.
A scope is one line, a -> lambda with plain or defaulted positional
parameters; any other scope line (a multi-line lambda, lambda do, a
proc, keyword or splat parameters) stops the generator, as does a
scope named like a column, a query method (where, count, first,
…) or another scope of the model.
234 |
# File 'cybertrain/model.rb', line 234 def self.scope(name, body) = nil |
.transaction(immediate: false) {|conn| ... } ⇒ nil
Cybertrain::DB.transaction, under the name Rails gives it: saves,
updates, destroys and queries run in the block (on this thread) are one
transaction, committed when the block returns and rolled back when it
raises. The block gets the connection, for SQL of its own.
Article.transaction do |c|
article.save!
Comment.create(article_id: article.id, body: "First!")
end
As with ActiveRecord, the transaction is the database’s, not the
model’s: Article.transaction and Comment.transaction are the same.
Unlike ActiveRecord it returns nil rather than the block’s value, a
save returning false does not roll anything back (raise, or use
save!), and there is no ActiveRecord::Rollback.
435 436 437 |
# File 'cybertrain/model.rb', line 435 def self.transaction(immediate: false, &block) Cybertrain::DB.transaction(immediate: immediate, &block) end |
.upsert(attrs, conflict:, update: {}) ⇒ Integer
Inserts one row, or, when it collides with an existing row on the
conflict columns (a UNIQUE index or the primary key), updates that
row instead: SQLite’s INSERT ... ON CONFLICT (...) DO UPDATE SET.
The counter-and-statistics shape in one statement.
attrs are column => value, bound, never interpolated; a generated
model casts each by its column’s type as a save does
(Relation.typed_bind: a decimal rounded to its scale, a boolean as
1/0, a Hash as JSON, a Time in the storage format) and refuses an
encrypted column (encrypts) among the attrs, the conflict columns
and the update keys, which only a save can encrypt. A hand-written
subclass binds through Cast.to_sql. update is column => SQL expression, where excluded.x
is the value this INSERT tried to write; like ArticleRelation#order_sql
it is the developer’s SQL text and must never see request data. An
empty update is DO NOTHING. Every column name (attrs, conflict,
update keys) must be a column name (Ident), or ArgumentError.
No model is built, no validation or callback runs, and
created_at / updated_at are not filled in: pass them in attrs
(and in update, updated_at: "excluded.updated_at") when the table
has them. Use Symbol keys throughout (NOTES rule 51).
44 45 46 47 |
# File 'cybertrain/model/bulk_writes.rb', line 44 def self.upsert(attrs, conflict:, update: {}) Model.upsert_into(table_name, attrs, conflict, update, Model.no_column_types, Model.no_decimal_scales, Model.no_encrypted_columns) end |
.validate(*args) ⇒ nil
Declares methods that validate the record by adding to #errors
themselves, run by #valid? after the validates rules:
validate :check_dates, :check_totals, on: :update, if: :published?,
unless: :imported?. The generator reads the line as text (like
scope) and writes run_custom_validations calling each method by
name; at run time this method does nothing. One line, Symbol method
names defined in the model file, and on: / if: / unless: with
literal values; a block or a lambda stops the generator.
190 |
# File 'cybertrain/model.rb', line 190 def self.validate(*args) = nil |
.validates(*args) ⇒ nil
Declares validations for one or more attributes, run by #valid?
(and so by #save) in declaration order, with Rails’ default English
messages (message: replaces them).
presence: true:"can't be blank"when the value isnilor a String that is empty afterstrip.falseand0are present.length: { minimum:, maximum:, is:, in: }(in:/within:an Integer Range):"is too short (minimum is n characters)","is too long (maximum is m characters)","is the wrong length (should be n characters)". Anilvalue is left topresence.inclusion: { in: }/exclusion: { in: }: an Array of Strings or Integers, or a Range of Integers (Spinel builds no other Range);"is not included in the list"/"is reserved".format: { with: /re/, without: /re/ }: the value as a String must matchwith:and must not matchwithout:, else"is invalid"(nil failswith:unlessallow_nil:, and passes awithout:rule alone).numericality: true | { only_integer:, greater_than:, greater_than_or_equal_to:, equal_to:, less_than:, less_than_or_equal_to:, other_than: }: a String is parsed as a number first ("12"passes,"abc"is"is not a number", as is nil);only_integertakes an Integer or an integer String ("must be an integer"; a Float fails it, as in Rails); each failing comparison adds"must be greater than 0"and so on, the limit as written.uniqueness: true | { scope: :column, case_sensitive: false }:"has already been taken"when another row holds the value (LOWER()on both sides when not case-sensitive; nil isIS NULL), through the generatedunique_value_taken?.- On every rule:
allow_nil:skips nil,allow_blank:nil and blank Strings;on: :create | :updateruns it for a new or a persisted record only;if:/unless:name a method of the model (a Symbol: the generator writes thevalidation_condition?table that calls it, and refuses a lambda and the:if =>/"if":spellings; a name the table lacks raises ArgumentError);message:replaces the default (also inside a rule’s Hash, for that rule).
An unknown option or a value of the wrong kind raises ArgumentError when the model loads, and the line declares nothing. For cross-field rules, name a method with validate.
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 |
# File 'cybertrain/model.rb', line 129 def self.validates(*args) built = Validator.build_all(args) list = (VALIDATORS[self.name] ||= Array.new(0) { Validator.new(:base, :presence) }) starts = (VALIDATES_STARTS[self.name] ||= Array.new(0) { 0 }) if MODEL_CONCERN_AT.key?(self.name) at = MODEL_CONCERN_AT[self.name] at = list.size if at > list.size built.each_with_index { |v, k| list.insert(at + k, v) } # The model's own calls from this one on start further along. starts.each_with_index { |s, k| starts[k] = s + built.size if s >= at } MODEL_CONCERN_AT[self.name] = at + built.size else starts << list.size built.each { |v| list << v } end nil end |
.validates_foreign_key(attr) ⇒ nil
The validation a declared belongs_to adds to its generated class:
“can’t be blank” on the foreign key while it is nil, blank or 0 (the
id of no saved record), so save returns false instead of the
database refusing the row.
323 324 325 326 327 |
# File 'cybertrain/model.rb', line 323 def self.validates_foreign_key(attr) list = (VALIDATORS[self.name] ||= Array.new(0) { Validator.new(:base, :presence) }) list << Validator.new(attr, :foreign_key) nil end |
Instance Method Details
#==(other) ⇒ Boolean
Records are equal when they are the same model and the same saved row. Two unsaved records are never equal, not even a record to itself.
741 742 743 744 |
# File 'cybertrain/model.rb', line 741 def ==(other) return false unless other.is_a?(Model) @id != 0 && @id == other.id && model_name == other.model_name end |
#as_json ⇒ Hash{String => Object}
#attributes, ready for JSON: a Time becomes its ISO 8601 String
("2026-10-05T09:00:00.000Z"); booleans, numbers, Strings and nil
stay as they are (Cast.to_sql would turn booleans into 1/0).
764 765 766 767 768 769 770 771 772 773 |
# File 'cybertrain/model.rb', line 764 def as_json out = {} attributes.each do |k, v| out[k] = case v when Time then Cast.iso8601(v) else v end end out end |
#attributes ⇒ Hash{String => Object}
Every column, keyed by its SQL name, "id" first, with typed values.
751 752 753 754 755 756 757 |
# File 'cybertrain/model.rb', line 751 def attributes attrs = { "id" => read_attribute(:id) } self.class.column_names.each do |column| attrs[column] = read_attribute(column.to_sym) unless column == "id" end attrs end |
#destroy ⇒ Boolean
Runs before_destroy, removes the dependent: children of
has_many / has_one, deletes the row, runs after_destroy, all
in one transaction (joining one already open): a raise anywhere rolls
every step back and the record stays #persisted?. Afterwards the
record keeps its attributes and id but is no longer #persisted?.
A record that was never saved has no row: destroy then runs no callbacks, sends no DELETE and returns false.
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 |
# File 'cybertrain/model.rb', line 705 def destroy return false unless @persisted begin if Cybertrain::DB.in_transaction? destroy_with_callbacks else Cybertrain::DB.transaction { |_c| destroy_with_callbacks } end rescue JSON::NestingError, JSON::ParserError, StandardError => e @persisted = true raise e end true end |
#errors ⇒ Errors
510 511 512 513 514 515 516 517 518 519 |
# File 'cybertrain/model.rb', line 510 def errors e = @errors return e unless e.nil? # The dictionary key full_messages and the validators look names # and messages up by ("post", "admin/post"; plan decision D9). e = Errors.new(Inflector.underscore(model_name)) @errors = e e end |
#new_record? ⇒ Boolean
Returns the opposite of #persisted?.
549 550 551 |
# File 'cybertrain/model.rb', line 549 def new_record? !@persisted end |
#persisted? ⇒ Boolean
Returns true once the record has been saved or was loaded from the database, false after #destroy.
543 544 545 |
# File 'cybertrain/model.rb', line 543 def persisted? @persisted end |
#reload ⇒ self
Re-reads every column from the database and forgets every association it had read (a belongs_to parent, a preload).
726 727 728 729 730 731 732 733 734 |
# File 'cybertrain/model.rb', line 726 def reload sql = "SELECT * FROM #{Relation.quote_ident(self.class.table_name)} WHERE #{Relation.quote_ident("id")} = ?" id = @id found = Cybertrain::DB.with { |c| c.execute_models(sql, [id]) } raise RecordNotFound, "Couldn't find #{model_name} with id=#{id}" if found.empty? load_row(found[0]) reset_association_caches self end |
#save ⇒ Boolean
Validates, then runs before_save, before_create/before_update, writes the row, and runs after_create/after_update and after_save – the ActiveRecord order. Returns false (and writes nothing) when invalid.
A new record is INSERTed (created_at / updated_at are filled in when
the table has them and they are nil) and gets its #id; a persisted one
is UPDATEd, every column, with updated_at set to now. Timestamps are
UTC, to the second.
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 |
# File 'cybertrain/model.rb', line 596 def save return false unless valid? run_callbacks("before_save") if @persisted # A counter_cache child reads its persisted key (before_update), # writes the row and moves the counts (after_update) in one # transaction, so a raise leaves the counters as they were. if counter_cached? && !Cybertrain::DB.in_transaction? Cybertrain::DB.transaction { |_c| update_with_callbacks } else update_with_callbacks end elsif counter_cached? && !Cybertrain::DB.in_transaction? # A counter_cache child writes the row and increments the parent's # count (after_create) in one transaction too. begin Cybertrain::DB.transaction { |_c| create_with_callbacks } rescue JSON::NestingError, JSON::ParserError, StandardError => e # Rolled back: the record is new again. @persisted = false @id = 0 raise e end else create_with_callbacks end run_callbacks("after_save") true end |
#save! ⇒ true
Like #save, but raises instead of returning false.
631 632 633 634 |
# File 'cybertrain/model.rb', line 631 def save! raise RecordInvalid, "Validation failed: #{errors..join(", ")}" unless save true end |
#to_json ⇒ String
#as_json as a JSON String, e.g. for render json: @article.to_json.
778 779 780 |
# File 'cybertrain/model.rb', line 778 def to_json JSON.generate(as_json) end |
#to_param ⇒ String
The id as a String, what route helpers put in a URL ("0" for a new
record).
557 558 559 |
# File 'cybertrain/model.rb', line 557 def to_param @id.to_s end |
#update(attrs) ⇒ Boolean
Assigns the attributes (cast to the column types, unknown keys ignored) and saves.
644 645 646 647 |
# File 'cybertrain/model.rb', line 644 def update(attrs) assign_attributes(attrs) save end |
#update_columns(attrs) ⇒ true
Writes the given columns straight to the row with one UPDATE of
exactly those columns, then keeps the new values on the record: no
validation, no callback, updated_at left alone. Each value is cast
as the attribute writer casts it and stored as #save would store it
(a decimal rounded to its scale, a Hash as JSON text). Keys are SQL
column names.
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 |
# File 'cybertrain/model.rb', line 662 def update_columns(attrs) raise ArgumentError, "update_columns: no attributes" if attrs.empty? raise ArgumentError, "update_columns: #{model_name} is not saved (a new record has no row)" unless @persisted names = Array.new(0) { "" } attrs.each do |key, _value| name = key.to_s unless name != "id" && column?(name) raise ArgumentError, "update_columns: #{name.inspect} is not a column of #{model_name}" end names << name end attrs.each { |key, value| write_attribute(key.to_s.to_sym, value) } # to_row's expressions for those columns: the generated casts and # scale rounding, read off the values just written. row = to_row sets = Array.new(0) { "" } binds = [nil, 0, 0.0, "", DB::Blob.new("")] binds.clear names.each do |name| sets << "#{Relation.quote_ident(name)} = ?" binds << row[name] end binds << @id table = Relation.quote_ident(self.class.table_name) id_column = Relation.quote_ident("id") set_list = sets.join(", ") sql = "UPDATE #{table} SET #{set_list} WHERE #{id_column} = ?" Cybertrain::DB.with { |c| c.execute(sql, binds) } true end |
#valid? ⇒ Boolean
Clears #errors, runs the before_validation callbacks, then every
rule declared with validates, then the validate methods. The
context is :create for a new record and :update for a persisted
one (rules with on: run in theirs only).
567 568 569 570 571 572 573 574 |
# File 'cybertrain/model.rb', line 567 def valid? errors.clear run_callbacks("before_validation") context = new_record? ? :create : :update Model.validators_for(model_name).each { |v| v.validate(self, context) } run_custom_validations(context) errors.empty? end |