I’m creating a relationship between a user and its profile like this in Rails
User has_one :profile
Profile belongs_to :user
I understand that under normal circumstances Rails automatically creates the foreign key relationship between those two models. However, when I am seeding the database with the information in the following way, with many Users created, and many Profiles created, then how do I ensure, for example, that Joe’s profile is linked with Joe’s user account.
User.create!(email: "j@gmail.com", password: "blahblah", encryptedpass: "3838")
Profile.create!(first_name: "Joe", last_name: "Frank", address: "43 Flint Road", phone: "604 345 678", )
User.create!(email: "anne@gmail.com", password: "blahblahblah", encryptedpass: "4567")
Profile.create!(first_name: "Anna", last_name: "Jones", address: "43 Boogy Road", phone: "604 345 678", )
…imagine thousands of users and profiles being seeded in this way….
Do i have to set a user_id foreign key on profile and, for the purposes of seeding it, do I just make up a foreign key id? Can rails generate it for me? If for example, I made a foreign key on Joe’s profile as user_id: 1 how can I be sure that his instance of the user model will be “1” In other words, if I manually set his user_id foreign key, how can I make sure it’ll match the id of the User model?
You can use
create_profile!method (which is created by Rails when you declarehas_one :profile