mardi 6 février 2018

How to seed join table data from yaml file through seed.rb in Rails

I am trying to add to my seed.rb the ability to load data onto a join table for my ROR 3.2.5 application.

I have two models: Saft.rb and Keyword.rb, which I would like to join.

class Saft < ActiveRecord::Base
   has_and_belongs_to_many :keyword, :join_table => "safts_keywords"
end

class Keyword < ActiveRecord::Base
  attr_accessible :word
  has_and_belongs_to_many :saft, :join_table => "safts_keywords"
end

I seed datasets for both from a yaml file, such as from: keywords_list.yml

---
  - word: "12"

  - word: "34"

The corresponding part of my Seed.rb:

keywords_data = YAML.load_file(Rails.root.join('db/seeds/keywords_list.yml'))
keywords_data.each do |keyword|
    h = Keyword.find_or_initialize_by_word(keyword['word'])
    h.save
end

Now I would like to seed the initial dataset for the join table from a yaml file too. (safts_keywords.yml)

---
  - saft_id: 1
    keyword_id: 2

When I try to load the data through:

# Load the Join Table
safts_keywords_data = YAML.load_file(Rails.root.join('db/seeds/safts_keywords_list.yml'))
safts_keywords_data.each do |saftkeyword|
    h = SaftKeyword.find_or_initialize_by_saft_id(saftkeyword['saft_id'], 
    :keyword_id => saftkeyword['keyword_id'])
    h.save
end

I get:

.
.
.
** Invoke db:structure:load_if_sql (first_time)
** Invoke db:create
** Execute db:structure:load_if_sql
** Invoke db:seed (first_time)
** Execute db:seed
** Invoke db:abort_if_pending_migrations (first_time)
** Invoke environment
** Execute db:abort_if_pending_migrations
rake aborted!
uninitialized constant SaftKeyword
/Users/Stephan/Development/REPRO/saftzine_com/db/seeds.rb:99
/Users/Stephan/Development/REPRO/saftzine_com/db/seeds.rb:97:in `each'
/Users/Stephan/Development/REPRO/saftzine_com/db/seeds.rb:97
.
.
.

How can I get this to work?

Aucun commentaire:

Enregistrer un commentaire