首页 > 解决方案 > 如何在 Rails 中的子模型中访问父模型 DB 道具(父父的 _id)?

问题描述

我在 Rails Ex 中有模型数据关系,4 个模型。Account、Role 和 Grant 模型分别属于 Account 和 RoleGrant 模型,它同时属于 Role 和 Grant 模型。现在,我需要访问 Role 的 account_id 和 Grant Model INSIDE RoleGrant Model 以比较他们的 account_id。

我非常努力,但即使经过数小时的搜索也无法解决这个问题。我知道我可以访问(例如在 Rails 控制台中)RoleGrant.last.role.account 并将获得具有我需要的 account_id 的帐户,但是如何在 RoleGrant 模型中执行此操作以验证 Role 和 Grant account_id 是否相同?

下面的代码显示了 RoleGrant 类,该类仅对 :role 和 :grant Model 进行验证。

class RoleGrant < ApplicationRecord
  # Description
  # An RoleGrant specifies an Grant within role

  # Includes
  include DefaultPolicyInfo

  # Relations
  belongs_to :role
  belongs_to :grant

  # Belongs_to Validation
  validates :role_id,
            presence: { if: -> { !role_id.nil? && role_id_changed? }, message: :not_valid },
            numericality: { allow_nil: false, only_integer: true, message: :numericality_not_blank }

  validates :grant_id,
            presence: { if: -> { !grant_id.nil? && grant_id_changed? }, message: :not_valid },
            uniqueness: { scope: %i[role_id] },
            numericality: { allow_nil: false, only_integer: true, message: :numericality_not_blank }

标签: rubyruby-on-rails-4model

解决方案


好吧,如果您想对此进行验证,建议您添加自定义验证,例如

def validate_same_account_ids
  errors.add(:base, 'Role and Grant account_ids do not match!') if role.account_id != grant.account_id
end

然后你可以调用这个 before_validation 所以像

before_validation :validate_same_account_ids

但是您可能还需要添加额外的检查,以查看您正在创建的 RoleGrant 记录中是否存在实际角色和授权


推荐阅读