Ruby on rails Rails 4-在没有数据库的情况下验证模型
我遵循了本教程,并尽我所能为Rails 4制作了它Ruby on rails Rails 4-在没有数据库的情况下验证模型,ruby-on-rails,database,model,ruby-on-rails-4,Ruby On Rails,Database,Model,Ruby On Rails 4,我遵循了本教程,并尽我所能为Rails 4制作了它 在我的控制器中: class ContactController < ApplicationController def index @contact = Contact.new end def create @contact = Contact.new(params[:contact]) if @contact.valid? # Todo send message here.
在我的控制器中:
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
class ContactController
在我看来:
<%= 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>
的未定义方法“name”#
您必须将它们声明为属性
属性访问者:姓名、电子邮件、电话、评论您可以使用ActiveAttr gem: Rails Cast教程: 例如:
class Contact
include ActiveAttr::Model
attribute :name
attribute :email
attribute :phone
attribute :comment
validates :name, :email, :phone, :comment, :presence => true
end
PS:我知道,这是一个老问题,但这可以帮助别人。在Rails 4及更高版本中,它实际上更简单:像这样使用:
class Contact
include ActiveModel::Model
attr_accessor :name, :email, :phone, :comment
validates :name, :email, :phone, :comment, :presence => true
end
class Contact
include ActiveModel::Model
attr_accessor :name, :email, :phone, :comment
validates :name, :email, :phone, :comment, :presence => true
end