Note that there are some explanatory texts on larger screens.

plurals
  1. PODB normalization fails with first_or_create or faulty assignments
    primarykey
    data
    text
    <p>This question is apparently trivial, but I am a newbie in Rails and I can't figure out where I get it wrong. I am populating associated models from an old spreadsheet. Below is a rake import task snippet. Somehow when location (Washington) is the same and already exists in the database for the Smith's post, the new assignment made for a second record <code>post.locations &lt;&lt; location</code> removes the location association with the Jones's post. My idea was to associate that same location with both people's posts. What am I missing?</p> <p><strong>import.rake</strong></p> <pre><code>data = [ { name: 'Jones', post: 'President', city: 'Washington' }, { name: 'Smith', post: 'Vice-President', city: 'Washington' }, { name: 'Peters', post: 'Janitor', city: 'New York' } ] data.each do |row| name = row[:name]; post = row[:post]; city = row[:city] person = Person.where(name: name).first_or_create post = Post.where(post: post).first_or_create location = Location.where(city: city).first_or_create post.people &lt;&lt; person post.locations &lt;&lt; location location.save; person.save; post.save end </code></pre> <p>The import above results in </p> <pre><code>person1 = Person.find_by_name("Jones"); person1.posts.first.locations.first == nil person2 = Person.find_by_name("Smith"); person2.posts.first.locations.first.city == "Washington" person3 = Person.find_by_name("Peters"); person3.posts.first.locations.first.city == "New York" </code></pre> <p><strong>location.rb</strong></p> <pre><code>class Location &lt; ActiveRecord::Base belongs_to :post attr_accessible :city end </code></pre> <p><strong>person.rb</strong></p> <pre><code>class Person &lt; ActiveRecord::Base attr_accessible :name has_many :occupations has_many :posts, through: :occupations end </code></pre> <p><strong>post.rb</strong></p> <pre><code>class Post &lt; ActiveRecord::Base attr_accessible :post has_many :occupations has_many :people, through: :occupations has_many :locations end </code></pre> <p><strong>occupation.rb</strong></p> <pre><code>class Occupation &lt; ActiveRecord::Base belongs_to :person belongs_to :post attr_accessible :person_id, :post_id, :since, :till end </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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