JamesRocky
JamesRocky

Reputation: 721

Rails: How do I "validates_presence_of" conditionally? For example when reaching a certain page?

For example I have a user registering, during registration all thats needed is a password and username. As soon as they click "shop", they must input address and city to continue.

At the moment every user must input username, password, city, and address to register. How do I split this and only require it if the user clicks "shop"?

I'm using devise.

I'd like to send the user to a page saying, "if you would like to continue, please let us know your address and city"

Upvotes: 0

Views: 228

Answers (2)

Venkatesh Dhanasekaran
Venkatesh Dhanasekaran

Reputation: 344

You can do that by nested forms for that and do custom validations in rails.

Ex:

class User < ActiveRecord::Base
 validates :my_method_name, if: :page_reached?

 def page_reached?
    -- do stuff for page number -- 
 end

 def my_method_name
    errors.messages :base, "Cities should not be empty."if cities.empty?
 end

 def my_method_name
    errors.messages :base, "Address should not be empty."if address.empty?
 end
end  

Upvotes: 1

BroiSatse
BroiSatse

Reputation: 44675

Just add a method to your model called can_shop? or similar checking if all required fields are given:

def can_shop?
  [city, address].all?(&:present?)
end

Then you can use this either to disable the button or to create a before_action in your controller:

before_action :check_if_can_shop

private

def check_if_can_shop
  return if current_user.can_shop?
  redirect_to edit_user_path(current_user), notice: "if you would like to continue, please let us know your address and city"
end

Naturally we are left with an UX element - you will need to mark those fields in the form as "optional, but required to shop". Later on you could pass original_url as an extra param, which you can then use to redirect user back to when he completed all the required fields.

Another thing is you could use validation contexts and use the right context in your user_update action - that way once you redirect user back to form, he will see proper validation errors when he miss normally-optional-but-now-required fields.

Upvotes: 4

Related Questions