Adnan Ali
Adnan Ali

Reputation: 2960

rails way to fetch records from same table with different types

I want to fetch three types of tickets from same table Ticket. Like this

Ticket.where(type: 'a').limit(5)
Ticket.where(type: 'b').limit(5)
Ticket.where(type: 'c').limit(5)

What is the best way in rails to get data equivalent to above three queries with minimum DB hits.

Upvotes: 1

Views: 426

Answers (2)

nonameg
nonameg

Reputation: 136

I think you need to use sql UNION query. You can see this answers: ActiveRecord Query Union

Or made all that things using just rails's sum. It's not elegant solution, but you can try that:

scope :by_type, ->(type){ where(type: type).limit(5) }

def self.foo
  Ticket.by_type('a') + Ticket.by_type('b') + Ticket.by_type('c')
end

Upvotes: 1

Pavan
Pavan

Reputation: 33542

You can use IN

types = [a,b,c]

Ticket.where("type IN (?)", types).limit(5)

Upvotes: 2

Related Questions