保存时,在has_many端获取当前对象

时间:2017-07-06 23:08:34

标签: ruby-on-rails ruby

我正在创建一个拥有许多设备的活动。我想验证设备模型。如何访问我目前正在保存的设备事件?我需要它来获取设备的使用日期(日期从事件模型中得知)。这是代码:

class Event < ApplicationRecord
    has_many :equipment_events, class_name: EquipmentEvent
    has_many :equipment, through: :equipment_events
end

class Equipment < ApplicationRecord
    has_many :equipment_events
    has_many :events, through: :equipment_events

    validate :equipment_already_used

  def equipment_already_used
     date = # <== HERE I need the date from this equipment's event that I am saving
  end

end

1 个答案:

答案 0 :(得分:0)

您需要将验证从Equipment移至EquipmentEvent,因为Equipment和Event是独立的实体。

class EquipmentEvent < ApplicationRecord

  belongs_to :equipment
  belongs_to :event

  validate :equipment_already_used

  def equipment_already_used
    event.date # <== HERE
  end

end