如何使用沒有數據庫表格的模型(比如聯繫表單)驗證表單(因此不需要標準記錄驗證)。使用模型驗證表單
我試過這個,但是我得到錯誤: undefined method
有效?'爲聯繫人:Class`
class Contact
include ActiveModel::Validations
attr_accessor :subject, :query
validates :subject, { :presence => { message:'Please select a subject' } }
validates :query, { :presence => { message:'Please enter your message' } }
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
def persisted?
false
end
end
然後方法:
def contact
@page_title = 'Contact Us'
end
def contact_email
if Contact.valid?
message = "#{params[:subject]}: #{params[:query]}"
current_user.send_contact_message(message)
redirect_to '/contact', notice: 'Thank you for your message, we will be in touch shortly.'
else
render :contact
end
end
的可能的複製[Rails的4 - 驗證模型沒有數據庫(http://stackoverflow.com/questions/16865821/rails-4-validate- model-without-a-database) –