I’ve 2 model, User and Client with the following relationship.
- User
has_many :clients - Client
belongs_to :user
How can I make all the registered users have their first :client_id => “1”, by default?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
So, you want all new users to default to the first client. You don’t want to set a default id number, what you want to do is set it to the
idof the firstClientin yourclientstable.So, in your
users_controller#newaction, all you have to do is set theclient_idfield to theidof the first client, like so:This makes it so that when the new
Userrecord is saved, unless the user has explicitly changed the value themselves, it will always point to the firstClientrecord in the database.The reason you don’t want to default it to
1is because if you do, and you ever destroy that client from the table, then aclient_idof1will point to a non-existent record, and your relationships will break for all new users after that happens. Even if you think that situation isn’t going to happen, it’s better to write your code in such a way that it can handle this situation, than to think it would never happen.