Bazley
Bazley

Reputation: 2847

Rails using 'where' to search association

I want to select all Notices that belong to the Character via the has_one association that have a nil supernotice. How do I code this?

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

Logs:

: 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"....

The logs show the error notices.commentee_id does not exist, but I've clearly stated in notice.rb that a notice has_one :supernotice through: :active_comment_relationship. Where am I going wrong?

Upvotes: 3

Views: 110

Answers (2)

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34338

You have a problem in your association in the first place.

When you define associations between two models, you have to set up properly in both of the models.

In your notice.rb Model, you have belongs_to :character association, so you have to define the counterpart of this association in your character.rb Model as well. You have to define a has_many or has_one association in your Character model which in your case is has_many notices.

So, in your character.rb Model, you need to define this association:

has_many :notices

When you setup the associations in both the models properly, then you can expect to get the correct result using:

self.notices.where(supernotice: nil) 

because now it knows how your Character model is associated with your Notice model.

I highly recommend you to read the Active Record Associations Guide

Upvotes: 0

Omar Lahlou
Omar Lahlou

Reputation: 1000

You need to add:

has_many :notices

In your character model.

Upvotes: 1

Related Questions