Very General Concept.
class User
include Mongoid::Document
field :name, :type => String
field :email_id, :type => Integer
field :active, :type => Boolean
field :status_id, :type => Integer
has_one :email
has_one :status
before_create :set_defaults
accepts_nested_attributes_for :email
validates :name, :status_id, :active, :presence => true
validates :email_id, uniqueness: true
private
def set_defaults
self.active = true
self.status = Status.where(name:"Published").first
end
end
class Email
include Mongoid::Document
field :email_address, :type => String
field :type, :type => String
field :status_id, :type => Integer
field :old, :type => Boolean
field :active, :type => Boolean
field :version, :type => Integer
has_one :status
before_create :set_defaults
validates :email_address, :type, :version, :status_id, :active, :presence => true
private
def set_defaults
self.type = "User Email"
self.version = 1
self.active = true
self.status = Status.where(name: "Published").first
end
end
def user_create
@user = User.new(user_params)
if @user.save
redirect_to action: :list
else
redirect_to action: :new_user
end
end
def user_params
params.require(:user).permit(:name, :alt_name, email:{:email_address})
end
You are also experiencing Issues because Email
has a field called email_id
as a String
which should be id
as an Integer
for the association to work properly. I changed this in my example so you can see. Now when you save a user the email record will also be created as an association to the User
.