Rails validation from controller
controller, model, ruby-on-rails, validation
Solution
you should use model without inheriting from `ActiveRecord::Base` class.
class ContactPageMessage
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :whatever
validates :whatever, :presence => true
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
def persisted?
false
end
end
Through this you will able to initialize new object and able to call validations on that object.
I think you have a different class name with same name, in your controller code, I can see this :
if ContactPageMessage.received(params).deliver
redirect_to contacts_path, :notice => "Success"
else
if this is your mailer class change its name to `ContactPageMessageMailer`. you will no loger get that error.
Hope it will help. Thanks
Problem
There is a contact page, which offers to enter name, telephone, email and message, after that it sends to an administrator's email. There is no reason to store message in DB. Question. How to: Use Rails validations in controller, not using model at all, OR Use validations in model, but without any DB relations UPD: Model: ``` class ContactPageMessage include ActiveModel::Validations include ActiveModel::Conversion extend ActiveModel::Naming attr_accessor :name, :telephone, :email, :message validates :name, :telephone, :email, :message, presence: true validates :email, email_format: { :message => "Неверный формат E-mail адреса"} def initialize(attributes = {}) attributes.each do |name, value| send("#{name}=", value) end end def persisted? false end end ``` controller: ``` def sendmessage cpm = ContactPageMessage.new() if cpm.valid? @settings = Setting.first if !@settings redirect_to contacts_path, :alert => "Fail" end if ContactPageMessage.received(params).deliver redirect_to contacts_path, :notice => "Success" else redirect_to contacts_path, :alert => "Fail" end else redirect_to contacts_path, :alert => "Fail" end end end ```