Γρήγορη αναφορά

Συνοπτικός οδηγός μοντέλων ActiveRecord του Rails

Ένας περιεκτικός οδηγός αναφοράς για μοντέλα Rails ActiveRecord: πεδία ερωτημάτων, συσχετίσεις, επικυρώσεις, callbacks, dirty tracking και συναθροίσεις.

· Δημοσιεύτηκε

Το ActiveRecord αντιπροσωπεύει το M (Model) στο Rails MVC, ενσωματώνοντας επιχειρηματική λογική, ερωτήματα βάσης δεδομένων, συσχετίσεις και κανόνες επικύρωσης.

Μέθοδοι Ερωτημάτων

# Βασικοί εντοπιστές (Finders)
User.find(1)                  # Εγείρει RecordNotFound εάν λείπει
User.find_by(email: '[email protected]')# Επιστρέφει nil εάν λείπει
User.first
User.last

# Συνθήκες και φίλτρα
User.where(active: true)
User.where.not(role: 'banned')
User.where('age >= ?', 18)

# Ταξινόμηση και περιορισμός
User.order(created_at: :desc).limit(10).offset(20)

# Πεδία ερωτημάτων (Scopes)
class User < ApplicationRecord
  scope :active, -> { where(active: true) }
  scope :recent, -> { order(created_at: :desc) }
end

Συσχετίσεις (Associations)

class Author < ApplicationRecord
  has_many :books, dependent: :destroy
  has_one :profile
  has_many :reviews, through: :books
end

class Book < ApplicationRecord
  belongs_to :author
  has_and_belongs_to_many :genres
end

Επικυρώσεις (Validations)

class User < ApplicationRecord
  validates :name, presence: true, length: { minimum: 2 }
  validates :email, presence: true, uniqueness: { case_sensitive: false }, format: { with: URI::MailTo::EMAIL_REGEXP }
  validates :age, numericality: { greater_than_or_equal_to: 13 }
  validates :role, inclusion: { in: %w[admin member guest] }
end

Callbacks

class Order < ApplicationRecord
  before_validation :normalize_currency
  before_create :generate_tracking_code
  after_create_commit :send_receipt_email

  private

  def normalize_currency
    self.currency = currency.upcase
  end
end

Παρακολούθηση αλλαγών (Dirty Tracking)

user = User.first
user.name = "New Name"

user.changed?        # => true
user.changed         # => ["name"]
user.changes         # => {"name" => ["Old Name", "New Name"]}
user.name_was        # => "Old Name"

Συναθροίσεις & Υπολογισμοί

Order.count
Order.sum(:total_amount)
Order.average(:rating)
Order.maximum(:price)
Order.minimum(:price)

Πηγές & Αναφορές

Σχετικά θέματα