Kotaa
Kotaa

Reputation: 201

Removing duplicates from a result set of ActiveRecord

I have this request:

res = Model1.joins(:items).where(items: {id: [1, 2, 3]})

It returns data with duplicates, although there're no duplicates in a database. How to remove duplicates from res?

Upvotes: 1

Views: 3175

Answers (2)

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34336

Use .uniq in Rails 4 and .distinct in Rails 5:

res = Model1.joins(:items).where(items: { id: [1, 2, 3] }).uniq

or,

res = Model1.joins(:items).where(items: { id: [1, 2, 3] }).distinct

Upvotes: 9

Robin Daugherty
Robin Daugherty

Reputation: 7534

An SQL join (using joins) gives you the product of two tables. If you're trying to get the Model1 records that are related to specific Item records, then use

Model1.where(item_id: [1, 2, 3])

Upvotes: -1

Related Questions