Rails 4: Forbid creating a parent object when associated one with specified attribute already exists

StackOverflow https://stackoverflow.com/questions/21699639

Pregunta

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

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

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

That prevents creating profile object with the same facebook_id. But it anyway creates a user object without any associated profile at all which is unwanted. How can I forbid creating a user object in this case?

¿Fue útil?

Solución

You could simply add a unique index on the database table of the SocialMedia model. Also you can add a validation:

validates_uniqueness_of :facebook_id

And in your User model you would test for presence and existence:

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

Also maybe this would already work:

validates_associated :social_media

should ensure that the associated record itself is valid.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top