Rails中的Active Record关联:初学者指南

作为Ruby on Rails开发人员,由于对象关系映射或ORM,我们不必太担心数据库中的操作。 ORM使我们可以更专注于业务逻辑,同时它代表我们处理数据库的操作。

了解关联对于创建可按预期方式运行并避免产生很大挫败感的Web应用程序至关重要。 在Rails中,关联是两个Active Record模型之间的连接。

假设有一个客户要求我们构建医院管理Web应用程序。 根据医院的需要,我们需要创建一些活动记录模型。

现在,让我们以其中的两个模型为例:一个用于医生,一个用于患者。 我们需要告诉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的新手,我希望这篇快速入门有助于澄清您对此主题的一些疑问。

From: https://hackernoon.com/understanding-active-record-associations-in-rails-6h642tpw

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值