簡體   English   中英

創建多態關聯has_many / has_one

[英]Creating polymorphic associations has_many/has_one

我有兩個導軌模型-發貨和注釋。 Notes是與主體和狀態的多態關聯。

貨件可以有很多票據。 has_many :notes, as: :notable

但是,我也想在Shipments中創建has_one關系,以顯示狀態不為null的最新筆記。

我嘗試了幾種不同的方法,但是沒有運氣,包括下面的代碼。 有人知道我該怎么做嗎? 我正在使用Rails 4上的ruby。請告知我是否可以提供其他信息。

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

也許您不需要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

您沒有外鍵...

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')

未經測試,但您可以嘗試類似的方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM