首页 > 解决方案 > 如何在检索具有 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_typeGarden为了防止不匹配。

什么是解决这个问题的好方法?

标签: ruby-on-railsruby-on-rails-5polymorphic-associations

解决方案


您可以使用 build_inis_a?方法检查关联的记录是什么。所以基本上你可以通过以下方式检查它是一个花园:

Note.find(1).garden.is_a? Garden

如果这是真的,你肯定它确实是一个花园。

只是一个提示:我会更改 has_one 的名称,因为这已经假设它是一个花园,而它可以是多态关系中的其他东西。


推荐阅读