I'm working on my first Rails(3) App, and looking to seed a bunch of data.
The issue I'm having is that I want to seed some models that have a has_and_belongs_to_many relationship with other models I've just seeded. I'm doing what seems right, but I'm not getting the results I'm expecting.
I have an Asana model (simplified):
class Asana < ActiveRecord::Base
has_and_belongs_to_many :therapeutic_foci
end
and the TherapeuticFocus model:
class TherapeuticFocus < ActiveRecord::Base
has_and_belongs_to_many :asanas
end
In my db/seeds.rb, I create some TherapeuticFoci:
tf = TherapeuticFocus.create([
{:name => 'Anxiety'},
{:name => 'Asthma'},
{:name => 'Fatigue'},
{:name => 'Flat Feet'},
{:name => 'Headache'},
{:name => 'High Blood Pressure'},
{:name => 'Stress'} ])
Then create an Asana:
asanaCreate = Asana.create!([
{ :english_name => 'Mountain Pose',
:traditional_name => 'Tadasana',
:pronunciation => 'TadaSANA',
:deck_set => 'Basic',
:type => 'Standing',
:therapeutic_foci => TherapeuticFocus.where("name in ('Stress','Flat Feet')")}
])
The result is that the TherapeuticFocus models are created, the Asana is created, but it doesn't create the relationships to the TherapeuticFocus models. The resulting array is empty.
If I run
TherapeuticFocus.where("name in ('Stress','Flat Feet')")
in the rails console, I get the expected two records:
irb(main):010:0> TherapeuticFocus.where("name in ('Stress','Flat Feet')")
=> [#<TherapeuticFocus id: 6, name: "Flat Feet", description: nil, created_at: "2010-10-11 01:48:02", updated_at: "2010-10-11 01:48:02">,
#<TherapeuticFocus id: 19, name: "Stress", description: nil, created_at: "2010-10-11 01:48:02", updated_at: "2010-10-11 01:48:02">]
So, how does one do this?
Or, is there a better way to do this?
Thanks!
POST ANSWER:
I had already added the inflection:
ActiveSupport::Inflector.inflections do |inflect|
inflect.irregular 'focus', 'foci'
end
My migration for the join tables looks like:
create_table :asanas_therapeutic_foci, :id => false do |t|
t.references :asana, :therapeutic_focus
end
I'll try changing this to t.belongs_to instead of t.references and see if that works.