content01
content01

Reputation: 3225

Rails3: Find records that have a relationship but exclude some by a specific value

Hi have two models (Rails3)

Aunt Friends

Where

aunt :has_many => friends

and

friend :belongs_to => aunt

Now, I want to get all aunts that are not related to friend X

I tried something like:

Aunt.includes(:friends).where('friends.id != ? ', X )

But it doesn't work.

PS: I also need to include the aunts that don't have any friends associated.

This is the output of :

@results = Aunt.custom(true).select('aunts.id, aunts.goal').joins("LEFT OUTER JOIN friends r ON aunts.id = r.aunt_id").where('r.other_value != ? or r.id is NULL', 4259 ).ordered_by_status_creation.select('aunts.id, aunts.goal')

SELECT aunts.id, aunts.goal FROM aunts LEFT OUTER JOIN friends r ON aunts.id = r.aunt_id WHERE aunts.deleted_at IS NULL AND leads.type IN ('MyType') AND (is_custom = 1) AND (r.another_value != 4259 or r.id is NULL) ORDER BY status desc, aunts.id desc

Any ideas?

Upvotes: 0

Views: 55

Answers (2)

minohimself
minohimself

Reputation: 526

U can use scope as following

scope :without_house, lambda { |param| param ? {:conditions => ["related_id != ?", param.id]} : {} }

Upvotes: 0

rainkinz
rainkinz

Reputation: 10394

I think you need something like this:

Aunt.joins("LEFT OUTER JOIN friends ON aunts.id = friends.friend_id").where('friends.id != ? or friends.id is NULL', X ).select

Upvotes: 0

Related Questions