Rubytastic
Rubytastic

Reputation: 15491

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

Upvotes: 4

Views: 12177

Answers (1)

deefour
deefour

Reputation: 35360

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.

Upvotes: 17

Related Questions