Rails ActiveRecord 参考
ActiveRecord 完整参考:迁移、关联、验证、回调、命名作用域和查询接口模式。
1. 迁移
class CreateArticles < ActiveRecord::Migration[7.1]
def change
create_table :articles do |t|
t.string :title, null: false, limit: 300
t.string :slug, null: false, index: { unique: true }
t.text :content, null: false
t.string :status, null: false, default: "draft"
t.jsonb :metadata, default: {}
t.references :author, null: false, foreign_key: { to_table: :users }
t.timestamps
end
end
end
2. 关联
class User < ApplicationRecord
has_many :articles, foreign_key: :author_id, dependent: :nullify
has_one :profile, dependent: :destroy
end
class Article < ApplicationRecord
belongs_to :author, class_name: "User"
has_many :comments, dependent: :destroy
has_and_belongs_to_many :tags
end
3. 验证
class Article < ApplicationRecord
validates :title, presence: true, length: { minimum: 5, maximum: 300 }
validates :slug, presence: true, uniqueness: true
validates :status, inclusion: { in: %w[draft published archived] }
validates :published_at, presence: true, if: :published?
validate :slug_not_reserved
private
def slug_not_reserved
errors.add(:slug, "是保留字") if %w[admin api].include?(slug)
end
end
4. 作用域与查询
class Article < ApplicationRecord
scope :published, -> { where(status: "published") }
scope :recent, -> { order(created_at: :desc) }
scope :search, ->(q) { where("title ILIKE ?", "%#{q}%") }
end
articles = Article.published.recent.page(1).per(20)
Article.includes(:author, :tags).where(tags: { name: "ruby" })