未定义的方法`include?' for nil:NilClass,部分验证向导gem

cyc*_*e87 10 validation ruby-on-rails formwizard ruby-on-rails-3

我试图遵循指南使用向导gem对对象进行部分验证,但我一直得到错误未定义的方法`include?' 对于nil:NilClass,无法理解有什么问题,已经尝试按照一步一步的说明进行操作.

日志中的错误显示.

NoMethodError - undefined method `include?' for nil:NilClass:
app/models/property.rb:22:in `active_or_tenants?'
Run Code Online (Sandbox Code Playgroud)

这是我的步骤控制器.

class Properties::BuildController < ApplicationController
  include Wicked::Wizard

  steps :tenant, :confirmed 

  def show
    @property = Property.find(params[:property_id])
    @tenants = @property.tenants.new(params[:tenant_id])
    render_wizard
  end

  def update
    @property = Property.find(params[:property_id])
    params[:property][:status] = step.to_s
    params[:property][:status] = 'active' if step == steps.last
    @property.update_attributes(params[:property])
    render_wizard @property
  end

  def create
    @property = current_user.properties.build(params[:property])
      logger.info @property.attributes
    if @property.save
        flash[:success] = "Tenant Added"
        redirect_to wizard_path(steps.second, :property_id => @property.id)
    else
        render 'edit'
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

Property.rb

class Property < ActiveRecord::Base
  attr_accessible  :name, :address_attributes, :tenants_attributes, :property_id, :status
  belongs_to :user 

  has_one :address, :as => :addressable
  accepts_nested_attributes_for :address, :allow_destroy => true

  has_many :tenants 
  accepts_nested_attributes_for :tenants, :allow_destroy => true

  validates :name,        :presence => true
  validates :address,     :presence => true
  validates :tenants,     :presence => true, :if => :active_or_tenants?

  def active?
    status == 'active'
  end

  def active_or_tenants?
    status.include?('tenants') || active?
  end
end
Run Code Online (Sandbox Code Playgroud)

如果您需要在问题中添加任何其他部分,请与我们联系.提前致谢.

MrY*_*iji 6

从我的评论:

status是您的Property模型的属性.nil在某些情况下可能会引发错误:

undefined method include?' for nil:NilClass
Run Code Online (Sandbox Code Playgroud)

它实际上是在尝试nil'tenants'(String)进行比较.

要解决这个问题,您可以使用空字符串进行比较,如果statusnil,

# an example (you can try in your IRB console):
nil || "No value"
# => returns "No value"
Run Code Online (Sandbox Code Playgroud)

在你的情况下:

def active_or_tenants?
  status.to_s.include?('tenants') || active?
end
Run Code Online (Sandbox Code Playgroud)

nil.to_s返回一个空字符串.这解决了你的问题;)


其实,方法to_s,to_i,to_f等经常被用来去除可能的nil:

# in ruby console:
2.3.3 :018 > nil.to_i
# => 0 
2.3.3 :019 > nil.to_f
# => 0.0 
2.3.3 :020 > nil.to_s
# => "" 
2.3.3 :021 > nil.to_a
# => [] 
Run Code Online (Sandbox Code Playgroud)