我有一个关于活动记录关联的问题,请参考rails文档的这一部分:
http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association
如果我们有三个型号:
class Physician < ActiveRecord::Base
has_many :appointments
has_many :patients, :through => :appointments
end
class Appointment < ActiveRecord::Base
belongs_to :physician
belongs_to :patient
end
class Patient < ActiveRecord::Base
has_many :appointments
has_many :physicians, :through => :appointments
end
Run Code Online (Sandbox Code Playgroud)
文档说可以通过api以这种方式管理连接模型的集合:
physician.patients = patients
Run Code Online (Sandbox Code Playgroud)
但是,如果约会模型(如链接示例中)有一个名为appointment_date的字段,并且我想在特定日期为医生和患者创建新约会,该怎么办?以下代码将在约会表中创建一条记录,但是如何在第三步中填充appointment_date呢?
physician = Physician.first
patient = Patients.first
physician.patients << patient
Run Code Online (Sandbox Code Playgroud)
这样的事情存在吗?
physician.patients.create( :patient => patient, 'appointment.appointment_time' => appointment_time )
Run Code Online (Sandbox Code Playgroud) 假设我有这个类(直接取自aasm文档):
class Job < ActiveRecord::Base
include AASM
aasm do
state :sleeping, :initial => true
state :running
state :cleaning
event :run do
transitions :from => :sleeping, :to => :running
end
event :clean do
transitions :from => :running, :to => :cleaning
end
event :sleep do
transitions :from => [:running, :cleaning], :to => :sleeping
end
end
end
Run Code Online (Sandbox Code Playgroud)
我不喜欢我的状态机定义与我的类定义混合的事实(因为当然在实际项目中我会向Job类添加更多方法).
我想在模块中分离状态机定义,以便Job类可以是以下内容:
class Job < ActiveRecord::Base
include StateMachines::JobStateMachine
end
Run Code Online (Sandbox Code Playgroud)
然后我在app/models/state_machines中创建了一个job_state_machine.rb文件,其内容类似于:
module StateMachines::JobStateMachine
include AASM
aasm do
state :sleeping, :initial => true
state :running
state :cleaning
event …Run Code Online (Sandbox Code Playgroud)