Reputation: 565
I am using Mongoid for the database in my Rails app. I've had this User model for a little while and now I just created a new Preference model where a User has_one preference and a Preference belongs_to a user. How do I create an instance of Preference for each of the existing users in my database?
SOLUTION:
I simply went to the Rails console and ran the following:
for user in User
unless Preference.find_by(user_id: user.id)
p = Preference.new(id: user.id, user_id: user_id)
p.save
end
end
Never imagined it could be this easy :)
Upvotes: 0
Views: 46
Reputation: 6321
It will create for you Preference
for each created user and id of user will be the same with preference !
In User.rb
before_create :set_preference
def set_preference
build_preference(id: self.id, user_id: self.id, email: self.email)
end
Upvotes: 1