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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With