rails 关联模型
作为Ruby on Rails开发人员,由于对象关系映射或ORM,我们不必太担心数据库中的操作。 ORM使我们能够更专注于业务逻辑,而它代表我们处理数据库的操作。
了解关联对于创建可按预期方式运行并避免产生很大挫败感的Web应用程序至关重要。 在Rails中,关联是两个Active Record模型之间的连接。
假设有一个客户要求我们构建医院管理网络应用程序。 根据医院的需要,我们需要创建一些活动记录模型。
现在,让我们以其中的两个模型为例:一个用于医生,一个用于患者。 我们需要告诉Rails,一名医生有很多病人,而一个病人可能有一名或多名医生,我们实现了这些低谷关联。
Rails支持六种类型的关联:
owners_to :特定于与另一模型(类)一对一(1:1)类型的关系。 仅当此类包含外键时,才可以使用此方法。 如果另一个类包含外键,则必须改用has_one
。
class DoctorOffice < ApplicationRecord
belongs_to :doctor
end
has_one :特定于与另一模型一对一(1:1)类型的关系。 仅当其他类包含外键时,才可以使用此方法。 如果当前类包含外键,则必须改用belongs_to
。
class Doctor < ApplicationRecord
has_one :doctor_office
end
has_many :指定一对多的关联(1:N)。 引用的模型必须实现belongs_to
。
class Doctor < ApplicationRecord
has_many :patients
end
has_many:trough :指定与另一个模型的多对多(N:M)关联。 这种关联表明, 通过进行第三个模型,可以将声明模型与另一个模型的零个或多个实例匹配。
class Doctor < ApplicationRecord
has_many :appointments
has_many :patients , through: :appointments
end
class Appointment < ApplicationRecord
belongs_to :doctor
belongs_to :patient
end
class Patient < ApplicationRecord
has_many :appointments
has_many :doctors , through: :appointments
end
has_one:trough :指定与另一个模型一对一(1:1)的关联。 这种关联表明声明模型可以通过进行第三种模型与另一种模型的一个实例进行匹配。
class Patient < ApplicationRecord
has_one :account
has_one :account_history , through: :account
end
class Account < ApplicationRecord
belongs_to :patient
has_one :account_history
end
class AccountHistory < ApplicationRecord
belongs_to :account
end
has_and_belong_to_many :指定多对多(N:M)与另一个模型的直接关联,而没有中间模型。
class Doctor < ApplicationRecord
has_and_belongs_to_many :patients
end
class Patient < ApplicationRecord
has_and_belongs_to_many :doctors
end
通常,如果您是Rails协会或Rails的新手,我希望这篇快速入门有助于澄清您对此主题的一些疑问。
翻译自: https://hackernoon.com/understanding-active-record-associations-in-rails-6h642tpw
rails 关联模型