Find records where association didnt already exists

how to get only records that isn't associated in Ebook model? Simply, i want to offer only ebooks that user didnt already have. I tried much solutions, one of best is:

Magazine.left_joins(:ebooks).where(ebooks: { id: nil })

but i dont know where to specify user_id

model Magazine
  has_many :ebooks
  has_many :users, :through => :ebook

model Ebook
  belongs_to :user
  belongs_to :magazine

model User
  has_many :ebooks

Im new in rails, sorry for stupid question maybe.

@Hass

thank you, but this generate sql like this:

SELECT "magazines".* FROM "magazines" 
INNER JOIN "ebooks" ON "magazines"."id" = "ebooks"."magazine_id" 
LEFT OUTER JOIN "ebooks" "ebooks_magazines" ON "ebooks_magazines"."magazine_id" = "magazines"."id" 
WHERE "ebooks"."user_id" = 1 AND "ebooks"."id" IS NULL 

(WHERE "ebooks"."user_id" = 1 => this returns 0 records, because where filter doesnt find any row in table ebooks)

but i need something like this:

SELECT "magazines".*, ebooks.user_id FROM "magazines" 
LEFT JOIN "ebooks" ON "magazines"."id" = "ebooks"."magazine_id" AND ebooks.user_id = 1
LEFT OUTER JOIN "ebooks" "ebooks_magazines" ON "ebooks_magazines"."magazine_id" = "magazines"."id" 
WHERE ebooks.user_id IS NULL

this returns rows that im looking for but i dont know how to do this with rais and associations

1 answer

  • answered 2020-09-24 15:50 Hass

    You want to use a left_outer_join instead.

    Magazine.left_outer_joins(:ebooks).where(ebooks: { id: nil })