I have a rails app where I'd like to populate the fields and associations of a model through a file upload. The user is presented with a form with a file upload input element, then after clicking submit, the rails app parses the file and uses it to build a number of other models.
A simplified example would look like this (note that for brevity this uses paperclip for the file upload):
class Parent < ActiveRecord::Base
has_many :children, :class_name => 'Child'
has_attached_file :attachment
after_initialize do |parent|
File.open(attachment.path) do |file|
process(file)
end
end
private
def process(attachment_file)
# create some new children using the attachment, perhaps this?
attachment_file.each_line |line|
# note that the children can either be new or existing.
self.children << Child.find_or_initialize_by_message(:message => line)
end
end
end
class Child < ActiveRecord::Base
belongs_to :parent
end
But my problem is that when I save my parent object, it's children don't save. (I'm using Rails 2.3.10 and Ruby 1.8.7)
What's strange is that it does work using Rails 2.3.4, but not in any version after that. Does anyone have any good suggestions for what I might be doing wrong? Or a better way to achieve the same thing?
Thanks in advance for your help - this is driving me nuts!