指南中的示例,它具有关联模型中的其他属性
class CreateAppointments < ActiveRecord::Migration
def change
create_table :physicians do |t|
t.string :name
t.timestamps null: false
end
create_table :patients do |t|
t.string :name
t.timestamps null: false
end
create_table :appointments do |t|
t.belongs_to :physician, index: true
t.belongs_to :patient, index: true
t.datetime :appointment_date
t.timestamps null: false
end
end
end
模型约会具有验证:
class Physician < ActiveRecord::Base
has_many :appointments
has_many :patients, through: :appointments
end
class Appointment < ActiveRecord::Base
belongs_to :physician
belongs_to :patient
validates :appointment_date, presence: true
end
class Patient < ActiveRecord::Base
has_many :appointments
has_many :physicians, through: :appointments
end
当我向医生添加患者时,some_physician.patient << some_patient
我必须进行定义appointment_date
。如何正确做?
如何正确做?
我认为,您可以定义一个方法,然后将该方法传递给before_save
回调。
class Appointment < ActiveRecord::Base
before_save :set_appointment_date
private
def set_appointment_date
self.appointment_date = Time.now
end
end
这样,您appointment_date
每次创建关系时就无需显式设置。它将自动为您设置。
编辑: before_save
如果以后要使用update
约会对象,也会触发,尽管这种情况非常少见。但是它将更新appointment_date
。为此,您可以使用before_create
回调,并且appointment_date
在这种情况下将仅被触摸一次。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句