2012-06-07 84 views
3

我有@invoices,其中包含與特定預定課程有關的所有發票。Rails 3.如何從查詢結果中刪除重複的關聯記錄?

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"> 

如何從結果中移除重複的對象?

+1

你就不能打電話uniq呢? – Sean

+0

使用uniq會將查詢轉換爲數組,這可能會對性能產生負面影響。 – yagooar

回答

8

您可以通過:uniq選項有很多:

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

下面是RoR的文檔此選項的說明:

如果爲真,重複將從收集被省略。與...一起使用。

此外,爲了避免在第一時間進入DB副本,您可以使用一個獨特的數據庫索引,這可能是這個樣子:

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

我喜歡這個解決方案。 – Kyle

+0

該解決方案將在Rails 4.0中被棄用,甚至可能在Rails 4.1中不存在,所以鼓勵使用替代lambda版本:has_many:invoices, - > {#get unique elements},:through =>:enrollments – yagooar

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

只使用@scheduled_course.invoices.uniq也應該工作。

+0

請記住,#uniq會將ActiveRecord關聯轉換爲發票數組,這會對獲取元素所需的性能和時間產生負面影響。 – yagooar

+0

是的,使用'distinct'代替。 –

相關問題