Ruby on rails 使用';其中';搜索关联

Ruby on rails 使用';其中';搜索关联,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,我想通过has one关联选择属于字符的所有通知,该关联具有nil超级通知。如何编写此代码 注意.rb: belongs_to :character has_one :active_comment_relationship, class_name: "Commentrelationship", foreign_key: "commenter_id",

我想通过
has one
关联选择属于
字符的所有
通知
,该关联具有
nil
超级通知
。如何编写此代码

注意.rb:

belongs_to :character

has_one  :active_comment_relationship, class_name: "Commentrelationship",
                                       foreign_key: "commenter_id",
                                       dependent: :destroy
has_one  :supernotice, through: :active_comment_relationship,
                       class_name: "Notice",
                       source: :commentee
accepts_nested_attributes_for :active_comment_relationship

has_many :passive_comment_relationships, class_name: "Commentrelationship",
                                         foreign_key: "commentee_id",
                                         dependent: :destroy
has_many :comments, through: :passive_comment_relationships,
                    class_name: "Notice",
                    source: :commenter 
character.rb:

has_many :notices

def topNotices
  self.notices.where(supernotice: nil)  # doesn't work
end
日志:

日志显示错误
通知。注释对象id
不存在,但我已在
notice.rb
中明确指出,通知
有一个:supernotice through::active\u comment\u relationship
。我哪里出错了?

您需要添加:

has_many :notices

在您的
角色
模型中。

首先,您的关联存在问题

定义两个模型之间的关联时,必须在两个模型中正确设置

notice.rb
模型中,您有
属于:character
关联,因此您还必须在
character.rb
模型中定义此关联的对应项。您必须在您的
字符
模型中定义一个
具有多个
具有一个
关联,在您的情况下,该模型是
具有多个通知

因此,在
character.rb
模型中,您需要定义此关联:

has_many :notices
在两个模型中正确设置关联后,可以使用以下方法获得正确的结果:

self.notices.where(supernotice: nil) 
因为现在它知道了你的
角色
模型是如何与你的
注意
模型相关联的


我强烈建议您阅读

我确实道歉,我确实有很多:注意事项
在我的角色模型中,我忘了把它放在问题中。我把这个问题搞砸了。恐怕我的问题没有解决。我已经编辑并改进了这个问题。日志显示Rails正在搜索
通知。评论id
,但我不明白为什么。我很抱歉,我的角色模型中有
有很多:通知,我忘了把它放在问题中。我把这个问题搞砸了。
活动注释关系中的外键和
中的源代码有一个:supernotice
是不同的值。如果外键是
commenter\u id
,那么源代码将是
commenter
。我刚刚在
notice.rb
中添加了更多细节。我不认为这是问题。
:supernotice
是通过
活动注释关系
建立的关系,该关系取决于
外键注释者id
。但是您已经将
超级通知的来源称为
评论
。因此,它会检查
commentee\u id
而不是
commenter\u id
。如果不相同,则类似:
self.notices.where(supernotice: nil)