创建多态关联has_many / has_one

时间:2017-07-06 18:44:48

标签: ruby-on-rails activerecord

我有两种导轨型号 - 发货和备注。 Notes是与主体和状态的多态关联。

货件可以有很多钞票。 (has_many :notes, as: :notable

但是,我还希望在“货件”中创建一个has_one关系,以显示状态为“空”的最新记事。

我尝试了一些不同的东西,但没有运气,包括下面的代码。谁知道我怎么做到这一点?我在铁轨上使用红宝石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'

2 个答案:

答案 0 :(得分:0)

也许你不需要一个has_one子句来实现这一点。我认为实现它的最佳方法是在笔记上创建几个范围:

<table class="table-lg">
  <tr>
    <td>content</td>
    <td>content</td>
    <td>content</td>
    <td>content</td>
    <td>content</td>
  </tr>
  <tr>
    <td>content</td>
    <td>content</td>
    <td>content</td>
    <td>content</td>
    <td>content</td>
  </tr>
</table>

<table class="table-md">
  <tr>
    <td>content</td>
    <td>content</td>
    <td>content</td>
    <td>content</td>
  </tr>
  <tr>
    <td>content</td>
    <td>content</td>
    <td>content</td>
    <td>content</td>
  </tr>
    <tr>
    <td colspan="2">content</td>
    <td colspan="2">content</td>
  </tr>
</table>

<table class="table-xs">
  <tr>
    <td>content</td>
    <td>content</td>
    <td>content</td>
  </tr>
  <tr>
    <td>content</td>
    <td>content</td>
    <td>content</td>
  </tr>
  <tr>
    <td>content</td>
    <td>content</td>
    <td>content</td>
  </tr>  
    <tr>
    <td colspan="3">content</td>
  </tr>
</table>

并在您的货件类中声明一个方法:

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

答案 1 :(得分: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')

未经测试,但你可以尝试这样的事情

相关问题