Rails 4: Prevent parenting if already associated with the specified attribute already exists

I have user and profile objects that have a one-to-one relationship. The profile object has the facebook_id parameter. I need to create a user through the nested attributes of the corresponding profile, unless the profile with the specified facebook_id already exists in the database.

Please help me with the right approach. I tried adding the following to my user.rb:

accepts_nested_attributes_for :social_profile#, :reject_if => proc {|attributes| Profile.where(:facebook_id=>attributes['facebook_id']).first}

This prevents the creation of a profile object with the same facebook_id. But it still creates a user object without any associated profile that is not undesirable. How can I prevent the creation of a custom object in this case?

+3
source share
1 answer

You can simply add a unique index to the database table of the SocialMedia model. You can also add confirmation:

validates_uniqueness_of :facebook_id

And in your User model, you must check for the existence and existence of:

validate_presence_of :social_media_id
validate :social_profile_exists

protected

def social_profile_exists
  errors.add(:social_media_id, "does not exist") unless SocialProfile.exists?(social_media_id)
end

Perhaps this has already worked:

validates_associated :social_media

must make sure that the corresponding entry is valid.

+1
source

All Articles