Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detect if a form is submitted with ruby on rails?

Is there a way to detect if a form is submitted? Im trying to set a class based on a custom validation something like below example, is that possible?

  .control-group{ :class => ("error" if form_is_submitted ) }

Now trying :

  .control-group{ :class => ("error" if params[:user][:profile_attributes][:gender] == nil) }

This fails if the form is not submitted because then the params are nill and throws an error

like image 369
Rubytastic Avatar asked Dec 04 '22 02:12

Rubytastic


1 Answers

If your form data is submitted through fields with name attributes like user[profile_attributes][gender] (all having the user prefix), you can check if the :user exists in params.

... if params.include?(:user)

If for some reason (like coming from the route) params[:user] is already going to have a value even for GET requests, you can look for a specific form field having a value. For example, you could add a hidden field

<%= f.hidden_field :some_field, :value => true %>

and check for it in your condition

... if params[:user].include?(:some_field)

You can alternatively check if the request is via the POST method

... if request.post?

This works for other methods as well, like request.put? for an update method.

like image 72
deefour Avatar answered Jan 15 '23 06:01

deefour