Validations on Form Object does not work, What is wrong with my code?
Please read the two cases posted. The first case has validation working, the second case does not.
Case 1
#Profile Model:
class Profile < ApplicationRecord
belongs_to :profileable, polymorphic: true
validates_presence_of :age
validates :age, numericality: { greater_than_or_equal_to: 0,
only_integer: true,
:allow_blank => true
}
end
Validation Test from Console:
p= Profile.new => #<Profile id: nil, age: nil>
p.age = "string" => "string"
p.save => False
p.errors.full_messages
=> ["Profileable must exist", "Age is not a number"]
Profile.create(age:"string").errors.full_messages
=> ["Profileable must exist", "Age is not a number"]
Validation directly on the model works
Case 2
#Form Object Registration:Profile:
module Registration
class Profile
include ActiveModel::Model
validates_presence_of :age
validates :age, numericality: { greater_than_or_equal_to: 0,
only_integer: true,
:allow_blank => true
}
attr_reader :user
delegate :age , :age=, to: :profile
def persisted?
false
end
def user
@user ||= User.new
end
def teacher
@teacher ||= user.build_teacher
end
def profile
@profile ||= teacher.build_profile
end
def save
if valid?
profile.save!
true
else
false
end
end
def submit(params)
profile.attributes = params.slice(:age)
if valid?
profile.save!
end
self
end
def self.model_name
ActiveModel::Name.new(self, nil, "User")
end
def initialize(user=nil, attributes={})
@user = user
end
end
end
#Profile Model:
class Profile < ApplicationRecord
belongs_to :profileable, polymorphic: true
end
Validation Test from Console on form object does not work
a=Registration::Profile.new(User.first)
a.age = "string"
a.save => true
a.errors.full_messages
=> []