【问题标题】:Rails 4 - Validate Model without a databaseRails 4 - 在没有数据库的情况下验证模型
【发布时间】:2013-05-31 20:54:11
【问题描述】:

我已按照本教程进行并尽我所能为 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>

【问题讨论】:

    标签: ruby-on-rails database model ruby-on-rails-4


    【解决方案1】:

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

    attr_accessor :name, email, :phone, :comment

    【讨论】:

      【解决方案2】:

      您可以使用 ActiveAttr gem: https://github.com/cgriego/active_attr

      Rails 铸造教程: 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:我知道,这是一个老问题,但这可以帮助某人。

      【讨论】:

        【解决方案3】:

        在 Rails 4 及更高版本中它实际上更简单:使用 ActiveModel::Model 代替:

        class Contact
          include ActiveModel::Model
          attr_accessor :name, :email, :phone, :comment
        
          validates :name, :email, :phone, :comment, :presence => true
        end
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-04-06
          • 1970-01-01
          • 2019-01-18
          • 2011-04-18
          • 1970-01-01
          • 1970-01-01
          • 2014-10-24
          • 1970-01-01
          相关资源
          最近更新 更多