How to verify that an association is valid

I have a model called Profile owned by the user, so there is "user_id" to track the database. In the local admin interface that I made for this model, I would like to provide flexibility that allows the administrator to enter the username in the field on the edit screen, and then allow user_id to save it in the controller.

However, the question is, how can I verify that the username has a valid return? I found that in ActiveRecord :: Validation there is no method to verify the existence of an association. How do you deal with this situation?

Update. What I want to do is check that the username field on the form is really a real user, then I can save this user_id back to admin editing. Here, "return" means the returned object of the user.

+4
source share
2 answers

This problem is a good candidate for virtual attributes. Instead of trying to resolve the username, let the profile model suit you.

class Profile belongs_to :user # ... def username user.try(:username) end def username=(value) self.user = User.find_by_username(value) end end 

Then in your form

 <% form_for @profile do |f| %> <%= f.text_field :username %> <% end %> 

When sending, the value of the username field is automatically transferred with all other valid activerecord attributes. ActiveRecord will look for username = setter and will allow communication. If the association returns nil (no record exists with the given username), then it will set the current user_id to nil, and the check will fail as expected.

You might want to tweak the error code to make it more meaningful.

EDIT: added example.

 validate :ensure_username_exists def username=(value) self.user_id = User.find_by_username(value) || 0 end protected def ensure_username_exists if user_id == 0 # nil is allowed errors.add(:user_id, "Username doesn't exists") return false end end 
+5
source

This is a useful link for associations with an active post: http://guides.rubyonrails.org/association_basics.html

To check for an association, just check connection.nil?

 if @profile.user.nil? ... something ... end 

To verify that the username is entered correctly, I'm not quite sure what you mean. Could you expand this?

+1
source

Source: https://habr.com/ru/post/1286408/


All Articles