Ruby on Rails - Nested Attributes and Automatic object creation

孤街醉人 提交于 2020-01-17 05:12:22

问题


I asked a previous question and this one follows...

I have 3 Models: Contract, Addendum and Appointment

Contract.rb
  has_many :addendums
  accepts_nested_attributes_for :addendums

Addendum.rb
  belongs_to :contract
  has_many :appointments

Appointment.rb
  belongs_to :addendum

When an Addendum is created, some Appointments are created automatically. I made this work adding a function on the Addendum's Controller like this

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

This function is called here

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

Now, because I start using the nested_attributes between Contract and Addendum, the new Addendum is created using the build method, so the function createNewAppointments is not called... How can I do this?

I tried using after_create createNewAppointments, on the model Addendum but it doesn't work. It gives an error Uninitialized constant Contract::Addendum


回答1:


you will have to move the method from the controller to the contracts model. Models can't access controllers methods.

And replace @addendum with self. Then call it from the controller with:

@addendum.createNewAppointments(params[:appointment], 'pendente')

Note that you need to pass the params from the controller to the model to make it work.

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

Your other option is to move the method to the contract controller wich is doing the work right now. As long as the addendums controller seems not to be interacting.

And do something like:

@addendum = contract.build....
create_new_appointments

HINT: Use rails conventions on naming methods. User lowercase underscores. Don't do JAVA naming.



来源:https://stackoverflow.com/questions/24397860/ruby-on-rails-nested-attributes-and-automatic-object-creation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!