2017-07-06 98 views
0

我有兩個導軌模型 - 貨件和註釋。 註釋是一個與身體和狀態的多態關聯。創建多態關聯has_many/has_one

一個貨件可以有許多鈔票。 (has_many :notes, as: :notable

但是,我還想在貨件中創建一個has_one關係以顯示狀態不爲null的最新備註。

我已經嘗試了幾個不同的東西,但沒有運氣,包括下面的代碼。任何人都知道我可以做到這一點?我在rails上使用ruby 4.請讓我知道我是否可以提供任何其他信息。

has_one :last_note_with_status, -> { where('notes.notable_type = Shipment') .where('notes.status is not null') .order(created_at: :desc) }, class_name: 'Note'

+0

這將是有益的,如果你能澄清哪個對象要返回時,大多數'Note'或'Shipment' – George

+0

我想根據Note.status返回貨件。 – Kam

回答

0

也許你並不需要一個HAS_ONE子句來實現這一目標。我認爲實現這一目標的最佳途徑是在筆記創建幾個範圍:

class Note 
    scope :latest, order(created_at: :desc).limit(1) 
    scope :with_status, where("status is not null") 
end 

,並在您的貨物類中聲明的方法:

class Shipment 
    def latest_note_with_status 
    notes.latest.with_status.first 
    end 
end 
+0

那麼我將如何獲得一個貨運集合,其中的票據狀態不是「已解決」?我需要循環收集並逐一檢查它們嗎? – Kam

+0

你可以爲它做另一個作用域..'scope:note_resolved,where.not(status:「Resolved」)'然後將它粘到你的查詢上'notes.latest.with_status.not_resolved.first' – Eric

+0

只需保持鏈接作用域。他們對這些東西非常有用 –

0

您沒有外鍵..

has_one :last_note_with_status, 
    -> { where(notable_type: 'Shipment').where.not(status: nil) }, 
    class_name: 'Note', 
    foreign_key: :notable_id 

這會給你一條記錄。從你想要什麼樣的聲音,這樣的事情可能工作:

scope: :last_unresolved, joins(:notes) 
    .where('notes.created_at = (SELECT MAX(notes.created_at) FROM notes WHERE notes.notable_id = shipments.id AND notes.notable_type = "Shipment")') 
    .where('notes.status NOT IN (?)', ["Delivered", "Resolved"]) 
    .where('shipments.status NOT IN (?)', ["Delivered", "Resolved"]) 
    .group('shipments.id') 

未經檢驗的,但你可以嘗試這樣的事情

+0

我也試過,但是當我用它在我的範圍內: '作用域:last_status_is_not_in, - >(){ statuses = [」 (「last_note_with_status.item_status not in(?)」,狀態) } 我收到以下錯誤消息。 'PG :: UndefinedTable:錯誤:缺少表「last_note_with_status」的FROM子句條目LINE 1:... ry_datetime>'2017-03-28 20:37:14.182266')AND(last_note _... ^' – Kam

+0

last_note_with_status不是一張桌子...上面的一段關係會給你的是能夠在你的對象上調用「last_not_with_status」......'Shipment.last.last_note_with_status' ...這將返回單個音符記錄......我不確定創建這種關係是否真的是你想要的...... – Eric

+0

如果我在貨運上運行範圍,我不應該收回集合嗎?如果我有一個範圍'範圍:晚, - >(){其中(「UPPER(status)!='DELIVERED')}'那麼我不應該能夠做一些像'Shipment.late.last_status_is_not_in'和它應該返回貨運表上沒有狀態「已交付」的貨物集合,並附上說明「已解決」或「已交付」的最後一個註釋?感謝您的幫助! – Kam