如何从上传的文件中填充activerecord模型(及其关联)

时间:2010-10-29 00:45:58

标签: ruby-on-rails activerecord

我有一个rails应用程序,我想通过文件上传填充模型的字段和关联。向用户显示带有文件上传输入元素的表单,然后在单击提交后,rails应用程序解析该文件并使用它来构建许多其他模型。

简化示例如下所示(请注意,为简洁起见,它使用回形针进行文件上传):

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

但我的问题是,当我保存我的父对象时,它的孩子不会保存。 (我使用的是Rails 2.3.10和Ruby 1.8.7)

奇怪的是,它确实可以使用Rails 2.3.4,但之后的任何版本都没有。对于我可能做错的事,有没有人有任何好的建议?或者更好的方法来实现同样的目标?

先谢谢你的帮助 - 这让我疯了!

1 个答案:

答案 0 :(得分:0)

试试这种方式!

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
相关问题