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

时间:2015-05-29 18:14:06

标签: ruby-on-rails ruby model-view-controller model controller

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

customer.rb

select count(id) as count_ones,user_id from table_name 
where chosen = 1 group by user_id order by count_ones desc limit 1

leads_controller.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

1 个答案:

答案 0 :(得分:1)

/* 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