Rails 来自控制器会话数据的模型中的条件验证

Rails Conditional Validation in Model from Controller Session Data

我正在尝试根据访问者是否参与测试来有条件地验证 full_namezip作为测试的一部分将具有某些会话数据)。我可以通过 customer.visitor_test() 将 true/false 从潜在客户控制器传递到客户模型,但我无法从 [=21= 访问 @test ]in_test? 在模型中。我错过了什么?

customer.rb

/* Stripped down code */

class Customer < ActiveRecord::Base
  attr_accessor    :test

  validates :full_name, presence: true, if: :not_in_test?
  validates :zip, presence: true, if: :in_test?

  def visitor_test(bool)
    @test = bool
  end

  def in_test?
    @test
  end

  def not_in_test?
    !self.in_test?
  end
end

leads_controller.rb

/* Stripped down code */

class LeadsController < ApplicationController
  def create
    session[:zip] = zip
    session[:email] = email
    session[:full_name] = full_name
    session[:email_opt_in] = email_opt_in
    session[:phone] = phone

    listing = Listing.where(id: listing_id).first

    customer = create_or_update_customer_from_session(listing)

    customer.visitor_test(/* true || false */)

    if customer.errors.blank?
      /* Do something */
    else
      /* Something else */
    end
  end
end
/* Stripped down code */

class Customer < ActiveRecord::Base
  attr_accessor    :test

  validates :full_name, presence: true, if: :not_in_test?
  validates :zip, presence: true, if: :in_test?

  def in_test?
    test
  end

  def not_in_test?
    !in_test?
  end
end

attr_accessor 提供 setter 和 getter.

/* Stripped down code */

class LeadsController < ApplicationController
  def create
    session[:zip] = zip
    session[:email] = email
    session[:full_name] = full_name
    session[:email_opt_in] = email_opt_in
    session[:phone] = phone

    listing = Listing.where(id: listing_id).first

    customer = create_or_update_customer_from_session(listing)         customer.test = true     

    customer.save

    if customer.errors.blank?
      /* Do something */
    else
      /* Something else */
    end
  end
end