Rowandish Rowandish - 1 year ago 65
Ruby Question

Load an ActiveRecord models from a YAML file



I'd like to create an ActiveRecord readonly model that is populated from a YAML file.
Here is my model:

class Building < ActiveRecord::Base

?right_callback_to_use? :load_data_from_yaml
after_initialize :readonly!

def load_data_from_yaml
#implementation?
end

end


And here is my yml

- id: 1
name: Building 1
- id: 2
name: Building 2


How can I load data from my external yml file and associate them with my model?

And how should I call my function
load_data_from_yaml
only once and only at the very beginning of my application?

I'm using Rails 4.

Thank you!

Answer Source

With the YAML structure you added to your question the below should work, assuming file.yml is the name of you YAML file

require 'yaml' #I think rails does this already for you so it might not be necessary

def load_data_from_yaml
  YAML.load_file("file.yml").each { |building| self.class.create!(building) }
end

if the size of your YAML file is huge and you want some speed you could have a look at: https://github.com/bjhaid/active_record_bulk_insert

and you method would look like this:

def load_data_from_yaml
  self.class.bulk_insert(YAML.load_file("file.yml"))
end
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download