我想通过Notices
Character
has_one
关联选择属于nil
的所有supernotice
。我该如何编码?
notice.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
日志:
: SELECT "notices".* FROM "notices" WHERE "notices"."character_id" = $1 AND "notices"."commentee_id" IS NULL ORDER BY "notices"."created_at" DESC
Completed 500 Internal Server Error in 316ms (ActiveRecord: 12.0ms)
ActiveRecord::StatementInvalid (PG::UndefinedColumn: ERROR: column notices.commentee_id does not exist
LINE 1: ..."notices" WHERE "notices"."character_id" = $1 AND "notices"....
日志显示错误notices.commentee_id
不存在,但我已在notice.rb
中明确说明了通知has_one :supernotice through: :active_comment_relationship
。我哪里错了?
答案 0 :(得分:1)
您需要添加:
has_many :notices
在character
模型中。
答案 1 :(得分:0)
您首先在协会中遇到问题。
定义两个模型之间的关联时,必须在两个模型中正确设置。
在notice.rb
模型中,您有belongs_to :character
关联,因此您还必须在character.rb
模型中定义此关联的对应关系。您必须在has_many
模型中定义has_one
或Character
关联,在您的情况下为has_many notices
。
因此,在character.rb
模型中,您需要定义此关联:
has_many :notices
当您在两个模型中正确设置关联时,您可以使用以下方法获得正确的结果:
self.notices.where(supernotice: nil)
因为它现在知道您的Character
模型与您的Notice
模型的关联。
我强烈建议您阅读Active Record Associations Guide