I have a model called Profile which is belong_to User, so there is ‘user_id’ for the database to keep track of. In the local admin interface I made for this model I wanted to provide the flexibility of allowing admin to enter an username to a field in the editing screen, and then resolve that to user_id for saving in controller.
However the question is, how do I check against that the username have a valid return? I found that in ActiveRecord::Validation there is no method for validating the existence of the association. How will you handle a situation like this?
Update: What I want to do is to validate that the username field in the form is indeed a real user, then I could save that user_id back to the profile admin is editing. Here ‘return’ means the user object returned.
This problem is a good candidate for virtual attributes.
Instead of trying to resolve the username, let the profile model to the job for you.
Then in your form
When submitted, the value for the username field is automatically passed with all the other real activerecord attributes. ActiveRecord will look for the username= setter and will resolve the association.
If the association returns nil (no record exists with given username), then it will set current user_id to nil and validation will fail as expected.
You might want to customize the error code to make more meaningful.
EDIT: Added example.