Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do you seed models with HABTM relationships to other seeded models
    text
    copied!<p>I'm working on my first Rails(3) App, and looking to seed a bunch of data.</p> <p>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.</p> <p>I have an Asana model (simplified):</p> <pre><code>class Asana &lt; ActiveRecord::Base has_and_belongs_to_many :therapeutic_foci end </code></pre> <p>and the TherapeuticFocus model:</p> <pre><code>class TherapeuticFocus &lt; ActiveRecord::Base has_and_belongs_to_many :asanas end </code></pre> <p>In my db/seeds.rb, I create some TherapeuticFoci:</p> <pre><code>tf = TherapeuticFocus.create([ {:name =&gt; 'Anxiety'}, {:name =&gt; 'Asthma'}, {:name =&gt; 'Fatigue'}, {:name =&gt; 'Flat Feet'}, {:name =&gt; 'Headache'}, {:name =&gt; 'High Blood Pressure'}, {:name =&gt; 'Stress'} ]) </code></pre> <p>Then create an Asana:</p> <pre><code>asanaCreate = Asana.create!([ { :english_name =&gt; 'Mountain Pose', :traditional_name =&gt; 'Tadasana', :pronunciation =&gt; 'TadaSANA', :deck_set =&gt; 'Basic', :type =&gt; 'Standing', :therapeutic_foci =&gt; TherapeuticFocus.where("name in ('Stress','Flat Feet')")} ]) </code></pre> <p>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.</p> <p>If I run</p> <pre><code>TherapeuticFocus.where("name in ('Stress','Flat Feet')") </code></pre> <p>in the rails console, I get the expected two records:</p> <pre><code>irb(main):010:0&gt; TherapeuticFocus.where("name in ('Stress','Flat Feet')") =&gt; [#&lt;TherapeuticFocus id: 6, name: "Flat Feet", description: nil, created_at: "2010-10-11 01:48:02", updated_at: "2010-10-11 01:48:02"&gt;, #&lt;TherapeuticFocus id: 19, name: "Stress", description: nil, created_at: "2010-10-11 01:48:02", updated_at: "2010-10-11 01:48:02"&gt;] </code></pre> <p>So, how does one do this? </p> <p>Or, is there a better way to do this?</p> <p>Thanks!</p> <p>POST ANSWER:</p> <p>I had already added the inflection:</p> <pre><code>ActiveSupport::Inflector.inflections do |inflect| inflect.irregular 'focus', 'foci' end </code></pre> <p>My migration for the join tables looks like:</p> <pre><code>create_table :asanas_therapeutic_foci, :id =&gt; false do |t| t.references :asana, :therapeutic_focus end </code></pre> <p>I'll try changing this to t.belongs_to instead of t.references and see if that works.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload