ruby - Rails Conditional Validation in Model from Controller Session Data -
i trying conditionally validate full_name , zip based on whether visitor part of test (visitors part of test have session data). able pass true/false leads controller customer model via customer.visitor_test(), can't access @test in_test? in model. missing?
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? /* */ else /* 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
provides 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? /* */ else /* else */ end end end
Comments
Post a Comment