Rails 4 – 在没有数据库的情况下validation模型

我已经按照本教程并尽可能地为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 

在我看来:

  : 
:

我收到此exception消息:

 undefined method `name' for # 

你必须将它们声明为属性。

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