Rails使用'where'来搜索关联

时间:2015-08-30 21:07:48

标签: ruby-on-rails activerecord

我想通过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。我哪里错了?

2 个答案:

答案 0 :(得分:1)

您需要添加:

has_many :notices

character模型中。

答案 1 :(得分:0)

您首先在协会中遇到问题。

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

notice.rb模型中,您有belongs_to :character关联,因此您还必须在character.rb模型中定义此关联的对应关系。您必须在has_many模型中定义has_oneCharacter关联,在您的情况下为has_many notices

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

has_many :notices

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

self.notices.where(supernotice: nil) 

因为它现在知道您的Character模型与您的Notice模型的关联。

我强烈建议您阅读Active Record Associations Guide