Rails 3.如何从查询结果中删除重复的关联记录?

时间:2012-06-07 18:56:25

标签: ruby-on-rails ruby activerecord

我有@invoices,其中包含与特定预定课程相关的所有发票。

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

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

现在,某些发票可能会重复。例如,@invoices - @scheduled_course.invoices可能会输出...

=> [#<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">

如何从结果中删除重复的对象?

2 个答案:

答案 0 :(得分:8)

您可以将:uniq选项传递给多个:

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

以下是此选项的RoR文档中的说明:

  

如果为true,将从集合中省略重复项。与以下内容结合使用:通过。

另外,为避免重复进入数据库,您可以使用唯一的DB索引,如下所示:

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

答案 1 :(得分:3)

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

只需使用@scheduled_course.invoices.uniq也可以。