【问题标题】:How to check the current model before retrieving a record with a has_one relationship如何在检索具有 has_one 关系的记录之前检查当前模型
【发布时间】:2019-05-14 03:26:24
【问题描述】:

给定以下多态关系:

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 以防止不匹配。

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

【问题讨论】:

  • 我认为多态关联是默认的。
  • 你能解释一下为什么这很有用吗? Note 并没有真正拥有一个花园,它可能属于也可能不属于 Garden,但它肯定没有花园的所有权,所以我试图更好地理解这个问题。

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


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多