leonel
leonel

Reputation: 10214

Rails 3. How to remove duplicate associated records from query result?

I have @invoices, which contains all invoices related to a particular scheduled course.

scheduled_course has_many :invoices, through => :enrollments
invoices belongs_to :scheduled_courses

@scheduled_course = ScheduledCourse.find(params[:id])
@invoices = @scheduled_course.invoices

Now, some invoices might be duplicated. For example, @invoices - @scheduled_course.invoices might output...

=> [#<Invoice id: 85, company_id: 106, invoice_number: "2870", issued_on: "2012-03-27", status: "pagado", notes: "", created_at: "2012-05-02 15:28:13", updated_at: "2012-05-02 15:50:50", exchange_rate: #<BigDecimal:c2bcc9c,'0.12E2',4(8)>, student_id: nil, due_date: "2012-04-02">, 
#<Invoice id: 85, company_id: 106, invoice_number: "2870", issued_on: "2012-03-27", status: "pagado", notes: "", created_at: "2012-05-02 15:28:13", updated_at: "2012-05-02 15:50:50", exchange_rate: #<BigDecimal:c2b828c,'0.12E2',4(8)>, student_id: nil, due_date: "2012-04-02">, 
#<Invoice id: 85, company_id: 106, invoice_number: "2870", issued_on: "2012-03-27", status: "pagado", notes: "", created_at: "2012-05-02 15:28:13", updated_at: "2012-05-02 15:50:50", exchange_rate: #<BigDecimal:c2b7e54,'0.12E2',4(8)>, student_id: nil, due_date: "2012-04-02">, 
#<Invoice id: 85, company_id: 106, invoice_number: "2870", issued_on: "2012-03-27", status: "pagado", notes: "", created_at: "2012-05-02 15:28:13", updated_at: "2012-05-02 15:50:50", exchange_rate: #<BigDecimal:c2b7a1c,'0.12E2',4(8)>, student_id: nil, due_date: "2012-04-02">, 
#<Invoice id: 85, company_id: 106, invoice_number: "2870", issued_on: "2012-03-27", status: "pagado", notes: "", created_at: "2012-05-02 15:28:13", updated_at: "2012-05-02 15:50:50", exchange_rate: #<BigDecimal:c2b75e4,'0.12E2',4(8)>, student_id: nil, due_date: "2012-04-02">, #<Invoice id: 85, company_id: 106, invoice_number: "2870", issued_on: "2012-03-27", status: "pagado", notes: "", created_at: "2012-05-02 15:28:13", updated_at: "2012-05-02 15:50:50", exchange_rate: #<BigDecimal:c2b7198,'0.12E2',4(8)>, student_id: nil, due_date: "2012-04-02">

How can I remove duplicated objects from the result?

Upvotes: 3

Views: 5923

Answers (2)

David Faber
David Faber

Reputation: 686

You can pass the :uniq option to has many:

has_many :invoices, :through => :enrollments, :uniq => true

Here's the description from the RoR docs for this option:

If true, duplicates will be omitted from the collection. Useful in conjunction with :through.

Also, to avoid duplicates from entering the DB in the first place, you may be able to use a unique DB index, which may look something like this:

add_index :enrollments, [:invoice_id, :scheduled_course_id], :unique => true

Upvotes: 8

Kyle
Kyle

Reputation: 22258

@scheduled_course.invoices.uniq(&:id) # uniq elements in the array by their id

Just using @scheduled_course.invoices.uniq should also work.

Upvotes: 3

Related Questions