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)