Mandatory fields depending on the form

Asked

Viewed 601 times

0

need to specify what will be mandatory depending on which form is displayed.

I have a Model that has some Ex fields.:

//Model User

:name, age, address:

In Create for User, only :name must be required. After the User is created, will have two links one will open a form in a modal requesting only the :age, and in this form the :age should be mandatory. And the other link will also open a form in a modal requesting only :address which in turn should also be required in this form.

How best that could be possible?

3 answers

1

I think the best way to do this is to validate with JS(Javascript), using the Required=true tag in HTML and putting a

validates :name, :age, :address presence: true

in the Model

0

You can create conditional methods in your model and handle conditional validations:

validates :campo, presence: true, if: campoo_obrigatorio?

def campo_obirgatorio?
 // retorno booleano
end

-2

I didn’t get to test it, but it doesn’t work that way?

  1. Set all fields as required
  2. In each controller action remove the methods you do not want

    def create
      if params[:user][:idade].blank?
        params[:user].delete(:idade)
      end
    
      if params[:user][:endereco].blank?
       params[:user].delete(:endereco)
      end
    end
    

Browser other questions tagged

You are not signed in. Login or sign up in order to post.