Pergunta

I am trying to create a has_one association among two model.

class User < ActiveRecord::Base
  has_one :emergency_contact
end

class EmergencyContact < ActiveRecord::Base
  belongs_to :user
end

when i try to test it through rails console more than one entries are saved for the emergency contact model for a single user. Although when i retrieve it using User.emergency_contact only the first entry is returned. When saving how can i make it to rollback for more than one entry

Foi útil?

Solução

You can simply validate uniqueness of user_id column in EmergencyContact:

class EmergencyContact < ActiveRecord::Base
  belongs_to :user
  validates_uniqueness_of :user_id, allow_nil: true
end
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top