views:

28

answers:

1

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!

A: 

Try this way!

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
krunal shah
Thanks for the hint! But I'm afraid that in simplifying my example I've missed out something important: in my case the children are added using an external class (I'm the builder design pattern) so it's really more like `Parent.children << Child.find_or_initialize_by_message(:message => line)`. So (I think) I'm already implicitly doing what you suggest.
tensaiji
Have you tried this code ? it has to work ..
krunal shah
My point is that this is what I am already doing (in the form `@parent.children << Child.find_or_initialize_by_message(:message => line)`)
tensaiji
What I would check is if the `children` actually has `Child` objects in them before its saved. One thing I noticed is if you are using the magic way of initializing the `Child` with `_by_message`, you should be able to just do: `Child.find_or_initialize_by_message(line)` as it expects the first parameter to be the message.
Garrett