Rails 实例本身的条件关联

Rails conditional association on instance itself

假设我们有一个 Comment 通过 belongs_to 关联连接到 Article。评论有一个名为 is_connected 的属性,它是一个布尔值。

我知道可以向 belongs_to 关系添加条件。是否可以在实例本身上添加条件?

class Comment
  belongs_to :article, -> {where: is_connected: true}
end

就像这个例子 - is_connected 正在引用文章模型。但我希望这种关系仅在 comment.is_connected == true

时才存在

我不知道你为什么有这种方法。我的意思是,如果一条评论中有 article_id,那么您可以放心地说这条评论与一篇文章相关联。 is_connected 似乎是重复的。 article_id present/absent 以同样的方式工作。

您可以定义条件验证:

belongs_to :article, optional: true
validates :article, presence: true, if: :is_connected

也可选择:

validates :article, absence: true, unless: :is_connected

或者,如果您希望关联仍被填充,但表现得好像没有填充,那么您需要定义一个自定义方法:

def connected_article
  is_connected ? article : nil
end