Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: What is the opposite of the build method? Or, can I destroy an object from memory before it's saved?

In Rails 3, if I have used build() to build an object, is there a way to destroy it before the object was ever saved?

The reason I need this is because I'm using a nested model form, with 3 generations of objects: Survey, which has many Questions, and Questions have many answers.

In the controller, I use build to pre-populate questions and answers.

The weird thing is, if the Survey model isn't valid, I re-render the page with the error messages, and the pre-built Questions appear in the form, but the not the Answers!

(I'm using Simple Form, by the way, if that's important.)

Anyway, I'd just destroy all the Questions before I rebuild them together with the answers, but how can you destroy the Questions if they haven't been saved to the database yet?

In my controller:

4.times do
  question = @survey.questions.build
  @answers.each { |answer| question.answers.build(:label => option.label, :input_type => option.input_type, :available_options => option.available_options) }
end

Any help would be greatly appreciated! Thanks!

like image 609
Rebitzele Avatar asked Nov 05 '22 14:11

Rebitzele


1 Answers

I don't have relations available at the moment, but why don't you try setting them to nil or an empty array? Like this:

@survey.questions = []

or

@survey.questions = nil
like image 148
Rhywden Avatar answered Nov 15 '22 11:11

Rhywden