Rails模型关联关系 #

一、关联类型 #

1.1 基本关联 #

关联类型 说明
belongs_to 属于
has_one 拥有一个
has_many 拥有多个
has_many :through 通过关联
has_one :through 通过关联一个

二、belongs_to #

2.1 基本用法 #

ruby
class Article < ApplicationRecord
  belongs_to :user
end

# 使用
article.user
article.user = User.first
article.build_user(name: 'John')
article.create_user(name: 'John')

三、has_many #

3.1 基本用法 #

ruby
class User < ApplicationRecord
  has_many :articles
  has_many :comments
end

# 使用
user.articles
user.articles << Article.new
user.articles.build(title: 'New Article')
user.articles.create(title: 'New Article')

四、has_many :through #

4.1 多对多关联 #

ruby
class User < ApplicationRecord
  has_many :subscriptions
  has_many :magazines, through: :subscriptions
end

class Subscription < ApplicationRecord
  belongs_to :user
  belongs_to :magazine
end

class Magazine < ApplicationRecord
  has_many :subscriptions
  has_many :users, through: :subscriptions
end

五、多态关联 #

5.1 定义多态关联 #

ruby
class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
end

class Article < ApplicationRecord
  has_many :comments, as: :commentable
end

class Photo < ApplicationRecord
  has_many :comments, as: :commentable
end

六、总结 #

6.1 核心要点 #

要点 说明
belongs_to 属于关联
has_many 一对多关联
has_many :through 多对多关联
多态关联 一个模型关联多种类型

6.2 下一步 #

现在你已经掌握了关联关系,接下来让我们学习 数据验证,深入了解Rails的模型验证!

最后更新:2026-03-28