有很多

has_many 關聯表示與另一個模型的一對多連線。該關聯通常位於 belongs_to 關聯的另一側。

此關聯指示模型的每個例項具有零個或多個另一個模型的例項。

例如,在包含使用者和帖子的應用程式中,可以像這樣宣告使用者模型:

class User < ApplicationRecord
  has_many :posts
end

Post 的表結構將與 belongs_to 示例中的表結構相同; 相比之下,User 不需要任何架構更改。

如果要獲取 User 的所有已釋出帖子的列表,則可以新增以下內容(即可以向關聯物件新增範圍):

class User < ApplicationRecord
  has_many :published_posts, -> { where("posts.published IS TRUE") }, class_name: "Post"
end