Reputation: 1047
I have a simple app with 3 models - Restaurant, Employee, and User. My Restaurant model has_many employees and I can hire other employees by creating them and giving a value to an attribute user_id of the employee. How to check for the presence of User with id=user_id before saving the new employee? Thank you!
EDIT======= The solution
validate :user_exists
def user_exists
if User.exists?(self.user_id)
return true
else
self.errors.add(:user_id, "Unable to find this user.")
return false
end
end
Upvotes: 0
Views: 626
Reputation: 11235
There's actually a simpler way of doing this since you can validate the belongs_to the association directly:
In Employee:
validates :user, presence: true, message: "could not be found"
Upvotes: 2
Reputation: 1047
It works with this code(No employee is created when the id is not found) but the error message is not showing...
validate :user_exists
def user_exists
if User.exists?(self.user_id)
return true
else
self.errors.add(:error, "Unable to find this user.")
return false
end
end
Upvotes: 0
Reputation: 2541
class Employee < ActiveRecord::Base
validate :user_exists, message: "#{user_id} must be a valid user"
def user_exists
return false if User.find(self.user_id).nil?
end
end
Upvotes: 1