Rom*_*man 14 validation controller model ruby-on-rails
有一个联系页面,提供输入姓名,电话,电子邮件和消息,然后发送给管理员的电子邮件.没有理由在DB中存储消息.
题.如何:
在控制器中使用Rails验证,完全不使用模型,或者
在模型中使用验证,但没有任何数据库关系
UPD:
模型:
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
Run Code Online (Sandbox Code Playgroud)
控制器:
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
Run Code Online (Sandbox Code Playgroud)
Rai*_*Guy 10
你应该使用模型而不继承自ActiveRecord::Base类.
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
Run Code Online (Sandbox Code Playgroud)
通过这个,您将能够初始化新对象并能够在该对象上调用验证.
我认为你有一个不同的类名同名,在你的控制器代码中,我可以看到:
if ContactPageMessage.received(params).deliver
redirect_to contacts_path, :notice => "Success"
else
Run Code Online (Sandbox Code Playgroud)
如果这是您的邮件程序类更改其名称ContactPageMessageMailer.你不会得到那个错误.
希望它会有所帮助.谢谢
我仍然建议你使用模型,rails模型不必继承ActiveRecord::Base.例如:
class Contact
include ActiveModel::Validations
attr_accessor :name, :telephone, :email, :message
validates_presence_of :name, :telephone, :email, :message
validates_format_of :email, with: EMAIL_REGEXP
end
Run Code Online (Sandbox Code Playgroud)
你可以在你的控制器中使用它:
contact = Contact.new
# ...
if contact.valid?
# do something
else
# do something else
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15059 次 |
| 最近记录: |