oyvindhauge
oyvindhauge

Reputation: 3673

How to check if model has existing model associations in Rails?

I have two ActiveRecord models (Book, Ad) which are associated. In my query I want to fetch books which has got 1 or more ads. What would be the best way to do this?

# in controller:
@books = Book.where(book has got 1 or more ads).last(20)

# Book model:
class Book < ActiveRecord::Base
   has_many :ads, :dependent => :destroy
   ...
end

# Ad model:
class Ad < ActiveRecord::Base
   belongs_to :book
   ...
end

Upvotes: 1

Views: 1221

Answers (3)

engineersmnky
engineersmnky

Reputation: 29318

Another simple solution would be

Ad.all.map{|ad| ad.book}.uniq.last(20)

This will return the last 20 unique books in an Array because if a Ad exists then it has a Book thus the Book has 1 or more Ads

Upvotes: 0

Said Kaldybaev
Said Kaldybaev

Reputation: 9952

in your controller

subquery = Ad.select("book_id").group(:book_id).having("COUNT(*) >= 1").to_sql
@books =   Book.where("id IN (#{subquery})").last(20)

Upvotes: 1

CDub
CDub

Reputation: 13344

One option is to use joins:

Book.joins(:ads)

joins allows you to do all of this in one query, and this would give you all Books that have a book_id on Ad set.

So for your controller, you'd have:

@books = Book.joins(:ads).last(20)

Upvotes: 3

Related Questions