ruby-on-rails - 如何在检索具有 has_one 关系的记录之前检查当前模型
问题描述
给定以下多态关系:
class Note < ApplicationRecord
belongs_to :noteable, polymorphic: true
has_one :garden, foreign_key: :id, primary_key: :noteable_id
end
class Garden < ApplicationRecord
has_many :notes, as: :noteable
end
我想验证这noteable_type
是Garden
为了防止不匹配。
什么是解决这个问题的好方法?
解决方案
您可以使用 build_inis_a?
方法检查关联的记录是什么。所以基本上你可以通过以下方式检查它是一个花园:
Note.find(1).garden.is_a? Garden
如果这是真的,你肯定它确实是一个花园。
只是一个提示:我会更改 has_one 的名称,因为这已经假设它是一个花园,而它可以是多态关系中的其他东西。
推荐阅读
- javascript - FlatList 在滚动时隐藏
- python - 如何使用 git bash 运行 python ('base' : conda) 脚本文件
- java - GitLab4j 如何从 GitLab 获取文件
- jsonschema - Json-Schema 演变:正在注册的模式与早期模式不兼容
- c# - 并行运行 WebApp 和 API 以执行 e2e 测试
- r - 使 shinyWidgets 输入大小取决于屏幕大小的最简单方法是什么?
- javascript - 使用 javascript 关闭窗口不起作用
- apache-spark - 使用特定的时间戳文字过滤 spark Dataframe
- node.js - 从 MongoDB 数据库中获取购物车详细信息
- reactjs - 如何解决 RollUp Material-ui “withStyles is not defined”