ActiveRecord

Нистратов Артём

anistratov@go-promo.ru

Validations

validates :email,
presence: true
    uniqunesses: true
    acceptance: true
    acceptance: { accept: 'yes' }
    confirmation: true
    format: {
        with: EMAIL_REGEX
    }
        message: "Невалидный Email"
    }
{ scope: :name }
length: { in: 5..200 }
length: {
    minimum: 10,
    maximum: 200,
    too_long: '%{count} too long',
    too_short: '%{count} too short'
}
    tokenizer: lambda { |str|
        str.split(/\s+/)
    },
numericality: true
numericality: {
    only_integer: true,
    greater_than: 10,
    greater_than_or_equal_to: 10,
    equal_to: 15,
    less_than: 100,
    less_than_or_equal_to: 100,
    odd: true,
    even: true
}
validates :nickname, allow_nill: true
allow_blank: true
validates :rules,
    acceptance: true,
    on: :create
    on: [:create, :publish]
record.valid? :publish
Proc.new do |*args|
  ...
end
proc { |*args| ... }
lambda { |*args| ... }
-> (*args) { ... }

Proc

validates :content,
    if: :content_changed?
validates :title, presence: true,
  if: -> (snippet) { snippet.public? }
validates :first_name, :last_name,
    presence: true,
    unless: "nickname.present?"
validate :langs_count
def langs_count
  if langs.count > 3
    errors.add :langs,
     'Указано слишком много языков'
  end
end

Validators

class ContentChecks < ActiveModel::Validator
  def validate(record)
    ...
    record.errors.add :content, 'Все плохо'
    ...
  end
end
validate_with ContentChecks

Callbacks

  • before_create
  • before_validation
  • after_validation
  • before_save
  • around_create
  • around_save
  • after_save
  • after_create
  • after_commit/after_rollback
  • before_destroy
  • around_destroy
  • after_destroy
  • before_update
  • around_update
  • after_update
before_create do
  ...
end
before_save :recalculate_dates,
    if: :event_at_changed?

def recalculate_dates
  ...
end
after_validation :check_permissions,
    if: -> (record) { ... }
after_commit :send_message,
    on: :create
save context: :publish
around_save do
  ...
  yield
  ...
end
has_many :snippets,
    after_add:    :update_statistic,
    after_remove: :update_statistic
after_initialize :set_defautls
after_touch :log
belongs_to :user, touch: true
class AuditCallbacks
  def before_save
    # log :changes
  end

  def after_destroy
    # log delete
  end
end
audit = AuditCallbacks.new
after_destroy audit
after_save    audit
class AuditObserver < ActiveRecord::Observer
  observe :snippet, :user
end

  def before_save(record)
    # log record.changes
  end

end

third

By adone

third

  • 807