Class: Article
- Inherits:
-
Cybertrain::Model
- Object
- Cybertrain::Model
- Article
- Defined in:
- docs/api/stubs/generated_app.rb
Overview
What spin run gen writes into gen/models/article.rb for this table in
db/schema.rb (the overview has the rules for
every table):
s.create_table "articles" do |t|
t.string "title"
t.text "body"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
The class is named after the singular of the table (articles → Article,
blog_posts → BlogPost), with one accessor per column, the finders below
and an association per foreign key. app/models/article.rb reopens it, with
no superclass, for validations (and
validate :method),
callbacks and your own methods; never edit
the generated file.
Attributes. Each column has a reader and a writer (article.title,
article.title = "x") holding a Ruby value of the column’s type:
| Schema type | Ruby value |
|---|---|
string, text |
String ("" for a new record when null: false, else nil) |
integer, references |
Integer (0 when null: false, else nil) |
float |
Float |
decimal |
Float, rounded to the column’s scale: when saved |
boolean |
true / false |
datetime |
Time (UTC), nil until set |
date |
Date (Date.new(2026, 10, 5), stored as "2026-10-05"), nil until set; invalid or blank input stays nil, and a null: false date without a default gets a generated presence validation, so save returns false with an error on the column |
json |
Hash with String keys ({} for a new record when null: false, else nil); its values read through Cybertrain::Cast.int, Cast.hash, Cast.array |
new, update and #write_attribute cast what they are given ("42"
becomes 42 for an integer column, "1"/"true"/"on" becomes true); the
plain writer article.title = ... does not. A schema default: that is a
plain literal becomes the initial value of a new record.
A column named like a model method or a Ruby keyword (errors, hash,
class) gets a reader named <column>_column, with a note in the
generated file; queries keep using the SQL name.
Encrypted columns. encrypts :body in app/models/article.rb
(Cybertrain::Model.encrypts) makes the generated load_row decrypt the
column (Cybertrain::Crypto.decrypt, decrypt_or_nil for a nullable one)
and to_row encrypt it, so the record holds the text and the table an
AES-256-GCM payload ("1:..."); ENCRYPTED_COLUMNS lists it and the
relation answers encrypted_column? for it, so where, where_like,
where_between, update_all and the bulk writes refuse it
(ArgumentError), while pluck answers the payload.
gen/app.rb then makes boot require CYBERTRAIN_ENCRYPTION_KEY
(Cybertrain::Config#encryption_key); the encryption itself
(cybertrain/encryptor, openssl) is in every program.
Associations come from foreign keys (t.references :article in a
migration, or add_reference): the table with the key gets a belongs_to
reader (Comment#article), the table it points to a has_many reader
(#comments). The app/models file can declare them too, to name them or
add options: has_many (dependent:),
has_one and
belongs_to (optional:, counter_cache:),
with class_name: and foreign_key:; includes
preloads them one level deep. There is no :through or polymorphic
association.
Class methods (finders) collapse
- COLUMN_TYPES =
Every column with its type (
idincluded), what the bulk writes cast by::integer,:float,:decimal,:boolean,:datetime,:date,:json,:binary,:string,:text, or:unknown. { "id" => :integer, "title" => :string, "body" => :text, "created_at" => :datetime, "updated_at" => :datetime }
- DECIMAL_SCALES =
The decimal columns that declare a
scale:, column => scale (none here). Cybertrain::Model.no_decimal_scales
- ENCRYPTED_COLUMNS =
The columns app/models/article.rb encrypts (
encrypts :name, as["name"]), which the bulk writes refuse as a row key and inreturning:,unique_by:andupdate_only:, and upsert in its attrs, conflict and update (none here). Cybertrain::Model.no_encrypted_columns
Instance Attribute Summary collapse
-
#body ⇒ String?
The
bodycolumn (t.text "body"). -
#created_at ⇒ Time?
Set by the first save when nil.
-
#title ⇒ String?
The
titlecolumn (t.string "title"). -
#updated_at ⇒ Time?
Set by every save.
Attributes inherited from Cybertrain::Model
Class methods (finders) collapse
-
.all ⇒ ArticleRelation
A relation over the whole table; every query starts here or at one of the shortcuts below.
-
.column_names ⇒ Array<String>
"id", then the SQL column names in schema order. -
.count ⇒ Integer
The number of rows in the table.
-
.create(attrs = {}) ⇒ Article
Builds a record and saves it.
-
.create!(attrs = {}) ⇒ Article
Builds a record and saves it with save!.
-
.find(id) ⇒ Article
The record with this id.
-
.find_by(conditions) ⇒ Article?
The first record matching the conditions (by id), or nil.
-
.find_by!(conditions) ⇒ Article
-
.first ⇒ Article?
The record with the lowest id.
-
.human_attribute_name(attr, options = {}) ⇒ String
An attribute’s name for people, as Rails’:
activerecord.attributes.article.<attr>in the current locale, else the attribute humanized (:author_id→"Author"). -
.includes(*names) ⇒ ArticleRelation
-
.insert_all(rows, returning: [:id], record_timestamps: true) ⇒ Array<Hash{String => Object}>
Inserts many rows in multi-row statements (
INSERT ... VALUES (...), (...) ON CONFLICT DO NOTHING RETURNING ...), as many rows per statement as SQLite’s bind limit allows (Cybertrain::DB::Connection#variable_limit), every statement in one transaction (joining one already open), so a failure leaves nothing of the call written; inside a transaction you opened, your rollback decides. -
.insert_all!(rows, returning: [:id], record_timestamps: true) ⇒ Array<Hash{String => Object}>
Article.insert_all without
ON CONFLICT DO NOTHING: a duplicate raises, and nothing of the call is written. -
.last ⇒ Article?
The record with the highest id.
-
.limit(n) ⇒ ArticleRelation
-
.order(order) ⇒ ArticleRelation
-
.order_sql(sql) ⇒ ArticleRelation
-
.preload(*names) ⇒ ArticleRelation
Same as Article.includes.
-
.table_name ⇒ String
The table,
"articles". -
.upsert(attrs, conflict:, update: {}) ⇒ Integer
Cybertrain::Model.upsert for this table: one row,
ON CONFLICT (conflict) DO UPDATE SETtheupdateexpressions. -
.upsert_all(rows, unique_by: [:id], update_only: nil, returning: [:id], record_timestamps: true) ⇒ Array<Hash{String => Object}>
Article.insert_all that updates a row colliding on
unique_byinstead of skipping it:ON CONFLICT (unique_by) DO UPDATE SET c = excluded.cfor every column the rows supply exceptid, theunique_bycolumns andcreated_at(only those inupdate_only, when given), plusupdated_atunlessrecord_timestamps: false. -
.where(cond = nil, *binds) ⇒ ArticleRelation
Every query method of ArticleRelation is also a class method, written as
def self.x(...) = all.x(...):where,where_like,where_between,order,order_sql,limit,offset,distinct,none,ids,find,find_by,find_by!,find_or_create_by,find_or_initialize_by,first,last,count,exists?,update_all,delete_all,destroy_all,find_each,pluck,pick,minimum_int,minimum_float,minimum_time,maximum_int,maximum_float,maximum_time,average, their_byforms,sum_int_by,sum_float_by,sum_float_sql,minimum_float_sql,maximum_float_sql,average_sql,having_sql,includes,preload,where_sql,pluck_str,pluck_int,pluck_float,count_by,count_by_sql,sum_int,sum_floatandincrement. -
.where_between(column, from, to, exclude_end: false) ⇒ ArticleRelation
-
.where_like(column, text) ⇒ ArticleRelation
Instance Method Summary collapse
-
#assign_attributes(attrs) ⇒ self
#write_attribute for each pair.
-
#comments ⇒ CommentRelation
has_many, from the foreign keycomments.article_id(or ahas_many :commentsline): this article’s comments, as the comments’ Relation, so it chains like any query and runs when rows are needed. -
#initialize(attrs = {}) ⇒ Article
constructor
A new, unsaved record.
-
#model_name ⇒ String
"Article". -
#read_attribute(name) ⇒ Object?
The value of a column by name, the way templates read it.
-
#unique_value_taken?(attr, value, scope_attr, scope_value, exclude_id, case_sensitive) ⇒ Boolean
What a
uniqueness:rule asks: whether another row holdsvaluein the columnattr. -
#write_attribute(name, value) ⇒ nil
Sets a column by name, casting the value to the column’s type.
Methods inherited from Cybertrain::Model
#==, after_create, after_destroy, after_save, after_update, #as_json, #attributes, before_create, before_destroy, before_save, before_update, before_validation, belongs_to, #destroy, encrypts, #errors, has_many, has_one, model_concern_insert_at, model_concern_insert_done, #new_record?, #persisted?, #reload, #save, #save!, scope, #to_json, #to_param, transaction, #update, #update_columns, #valid?, validate, validates, validates_foreign_key
Constructor Details
#initialize(attrs = {}) ⇒ Article
A new, unsaved record. Keys may be Strings or Symbols; values are cast
to the column types; unknown keys and id are ignored.
368 |
# File 'docs/api/stubs/generated_app.rb', line 368 def initialize(attrs = {}); end |
Instance Attribute Details
#body ⇒ String?
The body column (t.text "body").
378 379 380 |
# File 'docs/api/stubs/generated_app.rb', line 378 def body @body end |
#created_at ⇒ Time?
Set by the first save when nil.
383 384 385 |
# File 'docs/api/stubs/generated_app.rb', line 383 def created_at @created_at end |
#title ⇒ String?
The title column (t.string "title").
373 374 375 |
# File 'docs/api/stubs/generated_app.rb', line 373 def title @title end |
Class Method Details
.all ⇒ ArticleRelation
A relation over the whole table; every query starts here or at one of the shortcuts below. Nothing runs until rows are needed.
109 |
# File 'docs/api/stubs/generated_app.rb', line 109 def self.all = ArticleRelation.new("articles") |
.column_names ⇒ Array<String>
Returns "id", then the SQL column names in schema order.
87 |
# File 'docs/api/stubs/generated_app.rb', line 87 def self.column_names = ["id", "title", "body", "created_at", "updated_at"] |
.count ⇒ Integer
Returns the number of rows in the table.
202 |
# File 'docs/api/stubs/generated_app.rb', line 202 def self.count = all.count |
.create(attrs = {}) ⇒ Article
Builds a record and saves it. Returns the record whether or not it was saved: check persisted? or errors, or use create!.
227 228 229 230 231 |
# File 'docs/api/stubs/generated_app.rb', line 227 def self.create(attrs = {}) rec = Article.new(attrs) rec.save rec end |
.create!(attrs = {}) ⇒ Article
Builds a record and saves it with save!.
238 239 240 241 242 |
# File 'docs/api/stubs/generated_app.rb', line 238 def self.create!(attrs = {}) rec = Article.new(attrs) rec.save! rec end |
.find(id) ⇒ Article
The record with this id.
176 |
# File 'docs/api/stubs/generated_app.rb', line 176 def self.find(id) = all.find(id) |
.find_by(conditions) ⇒ Article?
The first record matching the conditions (by id), or nil.
184 |
# File 'docs/api/stubs/generated_app.rb', line 184 def self.find_by(conditions) = all.find_by(conditions) |
.find_by!(conditions) ⇒ Article
190 |
# File 'docs/api/stubs/generated_app.rb', line 190 def self.find_by!(conditions) = all.find_by!(conditions) |
.first ⇒ Article?
Returns the record with the lowest id.
194 |
# File 'docs/api/stubs/generated_app.rb', line 194 def self.first = all.first |
.human_attribute_name(attr, options = {}) ⇒ String
An attribute’s name for people, as Rails’:
activerecord.attributes.article.<attr> in the current locale, else the
attribute humanized (:author_id → "Author"). The model’s
dictionary key is its class name underscored (Admin::Post →
"admin/post"). See I18n.human_attribute_name.
101 |
# File 'docs/api/stubs/generated_app.rb', line 101 def self.human_attribute_name(attr, = {}) = I18n.human_attribute_name("article", attr) |
.includes(*names) ⇒ ArticleRelation
211 |
# File 'docs/api/stubs/generated_app.rb', line 211 def self.includes(*names) = all.includes(*names) |
.insert_all(rows, returning: [:id], record_timestamps: true) ⇒ Array<Hash{String => Object}>
Inserts many rows in multi-row statements (INSERT ... VALUES (...),
(...) ON CONFLICT DO NOTHING RETURNING ...), as many rows per statement
as SQLite’s bind limit allows (Cybertrain::DB::Connection#variable_limit),
every statement in one transaction (joining one already open), so a
failure leaves nothing of the call written; inside a transaction you
opened, your rollback decides. A row that collides with an
existing one on a UNIQUE index or the primary key is skipped silently.
Every row must have the same keys (Symbols or Strings, any order), or
ArgumentError before anything is written; columns no row names take the
table’s DEFAULT. Values take the casts a save gives them (a Time in the
storage format, a Hash as JSON text, a decimal rounded to its scale, a
Date as text, booleans as 1/0). created_at / updated_at, when the
table has them and the rows do not, get one now for the whole call
unless record_timestamps: false. No validation or callback runs.
296 297 298 299 |
# File 'docs/api/stubs/generated_app.rb', line 296 def self.insert_all(rows, returning: [:id], record_timestamps: true) Cybertrain::Model.insert_all_into("articles", rows, COLUMN_TYPES, DECIMAL_SCALES, ENCRYPTED_COLUMNS, returning, , :nothing, nil, nil) end |
.insert_all!(rows, returning: [:id], record_timestamps: true) ⇒ Array<Hash{String => Object}>
insert_all without ON CONFLICT DO NOTHING: a duplicate raises,
and nothing of the call is written.
310 311 312 313 |
# File 'docs/api/stubs/generated_app.rb', line 310 def self.insert_all!(rows, returning: [:id], record_timestamps: true) Cybertrain::Model.insert_all_into("articles", rows, COLUMN_TYPES, DECIMAL_SCALES, ENCRYPTED_COLUMNS, returning, , :raise, nil, nil) end |
.last ⇒ Article?
Returns the record with the highest id.
198 |
# File 'docs/api/stubs/generated_app.rb', line 198 def self.last = all.last |
.limit(n) ⇒ ArticleRelation
166 |
# File 'docs/api/stubs/generated_app.rb', line 166 def self.limit(n) = all.limit(n) |
.order(order) ⇒ ArticleRelation
154 |
# File 'docs/api/stubs/generated_app.rb', line 154 def self.order(order) = all.order(order) |
.order_sql(sql) ⇒ ArticleRelation
160 |
# File 'docs/api/stubs/generated_app.rb', line 160 def self.order_sql(sql) = all.order_sql(sql) |
.preload(*names) ⇒ ArticleRelation
Same as includes.
216 |
# File 'docs/api/stubs/generated_app.rb', line 216 def self.preload(*names) = all.preload(*names) |
.table_name ⇒ String
Returns the table, "articles".
83 |
# File 'docs/api/stubs/generated_app.rb', line 83 def self.table_name = "articles" |
.upsert(attrs, conflict:, update: {}) ⇒ Integer
Cybertrain::Model.upsert for this table: one row, ON CONFLICT
(conflict) DO UPDATE SET the update expressions. The values take
the casts a save gives them, as the bulk writes’ do, and an encrypted
column is refused among the attrs, the conflict columns and the
update keys (ArgumentError).
354 355 356 357 |
# File 'docs/api/stubs/generated_app.rb', line 354 def self.upsert(attrs, conflict:, update: {}) Cybertrain::Model.upsert_into("articles", attrs, conflict, update, COLUMN_TYPES, DECIMAL_SCALES, ENCRYPTED_COLUMNS) end |
.upsert_all(rows, unique_by: [:id], update_only: nil, returning: [:id], record_timestamps: true) ⇒ Array<Hash{String => Object}>
insert_all that updates a row colliding on unique_by instead of
skipping it: ON CONFLICT (unique_by) DO UPDATE SET c = excluded.c for
every column the rows supply except id, the unique_by columns and
created_at (only those in update_only, when given), plus
updated_at unless record_timestamps: false. A column the rows do not
supply keeps its value. unique_by must match a UNIQUE index or the
primary key.
336 337 338 339 |
# File 'docs/api/stubs/generated_app.rb', line 336 def self.upsert_all(rows, unique_by: [:id], update_only: nil, returning: [:id], record_timestamps: true) Cybertrain::Model.insert_all_into("articles", rows, COLUMN_TYPES, DECIMAL_SCALES, ENCRYPTED_COLUMNS, returning, , :update, unique_by, update_only) end |
.where(cond = nil, *binds) ⇒ ArticleRelation
Every query method of ArticleRelation is also a class method, written
as def self.x(...) = all.x(...): where, where_like,
where_between, order, order_sql, limit, offset, distinct,
none, ids, find, find_by, find_by!, find_or_create_by,
find_or_initialize_by, first, last, count, exists?,
update_all, delete_all, destroy_all, find_each, pluck,
pick, minimum_int, minimum_float, minimum_time, maximum_int,
maximum_float, maximum_time, average, their _by forms,
sum_int_by, sum_float_by, sum_float_sql, minimum_float_sql,
maximum_float_sql, average_sql, having_sql, includes,
preload, where_sql, pluck_str, pluck_int, pluck_float,
count_by, count_by_sql, sum_int, sum_float and increment. Not
delegated: or and not (they take or follow a relation), page, to_sql, and
to_a, each, size, empty?. The ones documented here are the
common ones.
135 |
# File 'docs/api/stubs/generated_app.rb', line 135 def self.where(cond = nil, *binds) = all.where(cond, *binds) |
.where_between(column, from, to, exclude_end: false) ⇒ ArticleRelation
140 |
# File 'docs/api/stubs/generated_app.rb', line 140 def self.where_between(column, from, to, exclude_end: false) = all.where_between(column, from, to, exclude_end: exclude_end) |
.where_like(column, text) ⇒ ArticleRelation
147 |
# File 'docs/api/stubs/generated_app.rb', line 147 def self.where_like(column, text) = all.where_like(column, text) |
Instance Method Details
#assign_attributes(attrs) ⇒ self
#write_attribute for each pair.
412 |
# File 'docs/api/stubs/generated_app.rb', line 412 def assign_attributes(attrs); end |
#comments ⇒ CommentRelation
has_many, from the foreign key comments.article_id (or a
has_many :comments line): this article’s comments, as the comments’
Relation, so it chains like any query and runs when rows are needed.
Add .to_a for an Array; templates iterate it as one. When two foreign
keys of one table point here, each reader is named
<table>_as_<key stem> (messages_as_sender).
When the article was loaded with Article.includes(:comments), the relation is created holding the
preloaded comments: to_a, each, first, last, size and
empty? answer from them without a query; count and exists? still
run SQL, and a chain method (where, order, limit, …) drops them
and queries as usual. reload forgets them.
433 434 435 436 437 438 |
# File 'docs/api/stubs/generated_app.rb', line 433 def comments rel = CommentRelation.new("comments").where(article_id: @id) return rel if @comments_preloaded.nil? rel.preloaded(@comments_preloaded) end |
#model_name ⇒ String
Returns "Article".
392 |
# File 'docs/api/stubs/generated_app.rb', line 392 def model_name = "Article" |
#read_attribute(name) ⇒ Object?
The value of a column by name, the way templates read it.
398 |
# File 'docs/api/stubs/generated_app.rb', line 398 def read_attribute(name); end |
#unique_value_taken?(attr, value, scope_attr, scope_value, exclude_id, case_sensitive) ⇒ Boolean
What a uniqueness: rule asks: whether
another row holds value in the column attr. Every model gets it,
built through the relation (the value is always a bind):
where(attr => value) – LOWER(attr) = LOWER(?) when
case_sensitive is false; a nil value is IS NULL either way –,
narrowed by where(scope_attr =>
scope_value) when a scope: is given, and where.not(id: exclude_id)
for a saved record, then exists?.
The model file’s if: / unless: names and validate :method lines
are generated too, as validation_condition?(name) (a case calling
the named method, raising ArgumentError for a name the file does not
declare; every model has one) and run_custom_validations(context) (each
validate method in order, under its on: / if: / unless:); a
name the model file does not define stops the generator.
468 |
# File 'docs/api/stubs/generated_app.rb', line 468 def unique_value_taken?(attr, value, scope_attr, scope_value, exclude_id, case_sensitive); end |
#write_attribute(name, value) ⇒ nil
Sets a column by name, casting the value to the column’s type. Unknown
names and :id are ignored.
406 |
# File 'docs/api/stubs/generated_app.rb', line 406 def write_attribute(name, value); end |