我问了之前的question,这个跟着......
我有3种型号:合同,附录和预约
Contract.rb
has_many :addendums
accepts_nested_attributes_for :addendums
Addendum.rb
belongs_to :contract
has_many :appointments
Appointment.rb
belongs_to :addendum
创建附录时,会自动创建一些约会。我做了这项工作在Addendum's Controller
这样添加了一个函数
def createNewAppointments
appointment = Appointment.new(params[:appointment]);
appointment.dataprovavel = @addendum.data
appointment.addendum_id = @addendum.id
appointment.appointment_state = AppointmentState.where(descricao:'Pendente').first
appointment.save
...
end
这个函数在这里调用
Addendum Controller
def create
respond_to do |format|
if @addendum.save
format.html { redirect_to @addendum, notice: 'Addendum was successfully created.' }
format.json { render action: 'show', status: :created, location: @addendum }
createNewAppointments
else
...
end
现在,因为我开始在合同和附录之间使用nested_attributes,所以使用build
方法创建新附录,因此不调用函数createNewAppointments
...我该怎么做?
我尝试在模型after_create createNewAppointments
上使用Addendum
,但它不起作用。它会出现错误Uninitialized constant Contract::Addendum
答案 0 :(得分:0)
您必须将方法从控制器移动到合同模型。模型无法访问控制器方法。
用自己取代@addendum。然后从控制器调用它:
@addendum.createNewAppointments(params[:appointment], 'pendente')
请注意,您需要将参数从控制器传递到模型以使其正常工作。
def createNewAppointments(appointment, descricao)
appointment = Appointment.new(params[:appointment]);
appointment.dataprovavel = self.data
appointment.addendum_id = self.addendum.id
appointment.appointment_state = AppointmentState.where(descricao: descricao).first
appointment.save
...
end
您的另一个选择是将方法移动到现在正在进行工作的合同控制器。只要附录控制器似乎没有交互。
做类似的事情:
@addendum = contract.build....
create_new_appointments
提示:在命名方法上使用rails约定。用户小写下划线。不要做JAVA命名。