ruby - 如何在 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 }
解决方案
好吧,如果您想对此进行验证,建议您添加自定义验证,例如
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 记录中是否存在实际角色和授权
推荐阅读
- php - 在具有 polylang 支持的 wordpress 中为登录用户和来宾用户设置不同的页面
- dart - DARTFMT 搞乱了@Component 装饰器格式
- java - 如何在 HTML 页面中部署 JavaFX 应用程序?
- python-2.7 - 在 matplotlib 3D scatter 中将一点放在前面
- r - stringr 是否使用一组不同的字符类作为标点符号?
- c - 通过 ref 从 struct 中的数组传回值
- cassandra - 在 Cassandra 中使用 UDT 会导致性能问题吗?
- json - 更新后如何保存我的 JSON 文件(重启程序后重置)
- sql - SQL Server 更新子查询的公式不太正确
- java - setServletContext 没有在@Configuration 文件中激活