PostgreSQL 在 Rails 回呼鏈中的哪個點分配任何資料庫(非空約束)默認值?
例如,我有一個Experiment模型,它有一個before_create回呼來設定experiment_type. 一個experimenthas_many Samples。如果在創建實驗時已經創建了樣本,則該實驗被視為與experiment_type樣本相同sample_type。否則,它會被分配資料庫的默認值。
class Experiment < ApplicationRecord
before_create :setup_exp_type
def setup_exp_type
sample_set = self.samples.first # An Experiment has_many samples
self.experiment_type ||= sample_set&.sample_type
end
資料庫表具有約束:
Column | Type | Collation | Nullable | Default | Storage | Stats target | Description
--------------------------- ----------------------------- ----------- ---------- --------------------------------------------------- ---------- -------------- -------------
id | integer | | not null | nextval('experiments_id_seq'::regclass) | plain | |
...
experiment_type | experiment_type | | not null | '1'::experiment_type | plain | |
控制器很簡單:
def create
@experiment = Experiment.new(experiment_params)
respond_to do |format|
if @experiment.save
format.html { redirect_to @experiment, notice: 'Experiment was successfully created.' }
format.json { render :show, status: :created, location: @experiment }
else
format.html { render :new }
format.json { render json: @experiment.errors, status: :unprocessable_entity }
end
end
end
假設樣本已經在實驗創建之前創建并分配給實驗,在setup_exp_type呼叫回呼時,我會假設尚未分配資料庫默認值,因為記錄仍然只在本地記憶體中。但是,在測驗中,我self.experiment_type = 1在除錯setup_exp_type. 在此之前沒有其他回呼,因此不會在源代碼中的任何其他地方分配它。
uj5u.com熱心網友回復:
在物件上呼叫 new 時會設定默認值,您可以在此處的方法源代碼中看到,
# File activerecord/lib/active_record/base.rb, line 1543
def initialize(attributes = nil, options = {})
@attributes = attributes_from_column_definition
@association_cache = {}
@aggregation_cache = {}
@attributes_cache = {}
@new_record = true
@readonly = false
@destroyed = false
@marked_for_destruction = false
@previously_changed = {}
@changed_attributes = {}
@relation = nil
ensure_proper_type
set_serialized_attributes
populate_with_current_scope_attributes
assign_attributes(attributes, options) if attributes
yield self if block_given?
run_callbacks :initialize
end
在第一行attributes_from_column_definition被稱為你可以在這里檢查
def attributes_from_column_definition
self.class.columns.inject({}) do |attributes, column|
attributes[column.name] = column.default unless column.name == self.class.primary_key
attributes
end
end
正如您在第二行中看到的那樣,它正在呼叫列默認值,該列在初始化時設定物件的默認值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/375550.html
標籤:红宝石轨道 PostgreSQL的 打回来
上一篇:查詢資料庫以獲取名字或姓氏
