I have a User model which has many roles. Roles contains a user_id field, which I want to validate_presence_of
The issue is: if I assign a role to user upon create, the validation fails because no user_id is set. Now, I do want to validate that a user_id exists, but I need to save the user before checking that.
The code currently looks like this:
@user = User.new(params[:user])
@user.roles << Role.new(:name => 'Peon') unless @user.has_roles?
if @user.save
# ...
The only ways I can think of getting around the problem involves either disabling the validation, which I don’t want to do, or double-saving to the DB, which isn’t exactly efficient.
What’s the standard way for handling this issue?
I think you can get around the validation problem if you change your code to look like this:
If that doesn’t work, you could try changing you validation to this: