[英]Rails 4 - Validate Model without a database
我已經按照本教程進行了學習,並為Rails 4盡了最大努力。
http://railscasts.com/episodes/219-active-model?language=en&view=asciicast
class Contact
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
validates :name, :email, :phone, :comment, :presence => true
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
def persisted?
false
end
private
# Using a private method to encapsulate the permissible parameters is just a good pattern
# since you'll be able to reuse the same permit list between create and update. Also, you
# can specialize this method with per-user checking of permissible attributes.
def contact_params
params.require(:contact).permit(:name, :email, :phone, :comment)
end
end
在我的控制器中:
class ContactController < ApplicationController
def index
@contact = Contact.new
end
def create
@contact = Contact.new(params[:contact])
if @contact.valid?
# Todo send message here.
render action: 'new'
end
end
end
在我看來:
<%= form_for @contact do |f| %>
<%= f.label :name %>:
<%= f.text_field :name %><br />
<%= f.label :email %>:
<%= f.text_field :email %><br />
<%= f.submit %>
<% end %>
我收到以下異常消息:
undefined method `name' for #<Contact:0x007fd6b3bf87e0>
您必須將它們聲明為屬性。
attr_accessor:名稱,電子郵件,:電話,:評論
您可以使用ActiveAttr gem: https : //github.com/cgriego/active_attr
Rails Cast教程: http : //railscasts.com/episodes/326-activeattr
例:
class Contact
include ActiveAttr::Model
attribute :name
attribute :email
attribute :phone
attribute :comment
validates :name, :email, :phone, :comment, :presence => true
end
PS:我知道,這是一個老問題,但這可以幫助某人。
在Rails 4及更高版本中,它實際上更簡單:像下面這樣使用ActiveModel :: Model :
class Contact
include ActiveModel::Model
attr_accessor :name, :email, :phone, :comment
validates :name, :email, :phone, :comment, :presence => true
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.