验证没有数据库的模型

验证没有数据库的模型

本文介绍了Rails 4 - 验证没有数据库的模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经遵循这个教程,并尽可能为Rails 4成型。








  class Contact 
include ActiveModel :: Validations
include ActiveModel: :
extend ActiveModel :: Naming

validates:name,:email,:phone,:comment,:presence => true

def initialize(attributes = {})
attributes.each do | name,value |
send(#{name} =,value)
end
end

def持久化?
false
end

private
#使用私有方法封装允许的参数只是一个好的模式
#,因为你将能够在创建和更新之间重用相同的许可列表。此外,
#可以专门化此方法,每个用户检查允许的属性。
def contact_params
params.require(:contact).permit(:name,:email,:phone,:comment)
end
end

在我的控制器中:

  ContactController< ApplicationController 
def index
@contact = Contact.new
end

def create
@contact = Contact.new(params [:contact])
if @ contact.valid?
#Todo在这里发送消息。
render action:'new'
end
end
end


$ b b

在我的视图中:

 <%= form_for @contact do | f | %> 
<%= f.label:name%>:
<%= f.text_field:name%>< br /

<%= f.label:email%> ;:
<%= f.text_field:email%>< br /

<%= f.submit%>
<%end%>






我收到此异常消息:

 未定义方法`name'for#< Contact:0x007fd6b3bf87e0> 


解决方案

您必须将它们声明为属性。 >

attr_accessor:name,email,:phone,:comment


I've followed this tutorial and molding it as best I can for 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

In my Controller:

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

And in my View:

<%= form_for @contact do |f| %>
    <%= f.label :name %>:
    <%= f.text_field :name %><br />

    <%= f.label :email %>:
    <%= f.text_field :email %><br />

    <%= f.submit %>
<% end %>


I'm getting this exception message:

undefined method `name' for #<Contact:0x007fd6b3bf87e0>
解决方案

you have to declare them as attributes.

attr_accessor :name, email, :phone, :comment

这篇关于Rails 4 - 验证没有数据库的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 14:44