0

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 
0

3 Answers 3

2

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"

Sign up to request clarification or add additional context in comments.

1 Comment

It's my fault that I didn't put the models but there is no association between the employee and user.However, it might be a good idea to do say that each user has_many employees (doesn't sound good, though..) Thanks :)
1
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 

2 Comments

Please provide some context instead of just answering with a code block.
It was almost right. Thanks a lot! However, the message does not work and I had to change the method a bit. Now, I only have to figure out how to fix the error message...
0

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 

1 Comment

what about using the :user_id attribute to error message ? self.errors.add(:user_id, "Unable to find this user.")

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.