Preloading data without messing up association when data is loaded the 2nd time.

Posted by denniss on Stack Overflow See other posts from Stack Overflow or by denniss
Published on 2010-12-28T09:49:13Z Indexed on 2010/12/28 9:53 UTC
Read the original article Hit count: 220

This is how my model looks like

User
belongs_to :computer

Computer
has_many :user

Users are created when people register for an account on the web site but computers are pre-loaded data that I create in seeds.rb/some .rake file. All is fine and good when the app is first launched and people start registering and get associated with the right computer_id. However, suppose I want to add another computer to the list

Computer.destroy_all
Computer.create({:name => "Akane"})
Computer.create({:name => "Yoda"})
Computer.create({:name => "Mojito"}) #newly added

running the rakefile the second time around will mess up the associations because computer_id in the User table refer to the old id in Computer table. Since I have run the script above, the id keeps incrementing without any regard to the association that user has to it.

Question: Is there a better way for me to pre-load data without screwing up my association? I want to be able to add new Computer without having to destroy the user's table. Destroying the computer table is fine with me and rebuilding it again but the old association that the existing users have must stay intact.

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ruby-on-rails3