0

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
  • This Addendum Controller means class AddendumsController? Commented Jun 25, 2014 at 0:20

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.