Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails validation from controller

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:

  1. Use Rails validations in controller, not using model at all, OR

  2. 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
like image 602
Roman Avatar asked Jul 31 '13 08:07

Roman


1 Answers

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

like image 84
Rails Guy Avatar answered Oct 18 '22 07:10

Rails Guy