Home > Mobile >  Submit a parameter via form_for that isn't an attribute on the model instance?
Submit a parameter via form_for that isn't an attribute on the model instance?

Time:05-24

I have a relatively simple question. I have a form_for which works nicely, I'd like to pass through a random parameter that doesn't belong to the User model, nor to any associated model (e.g. it shouldn't rely on accepts_nested_attributes_for).

When I try to add it to the form:

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>

<h2>Sign up</h2
  
  <%= f.label :first_name %>
  <%= f.text_field :first_name %>

  <%= f.label :foo %>
  <%= f.text_field :foo %>

  <%= f.submit "Sign up" %>

<%= render "devise/shared/links" %>
<% end %>

The view is loaded with this error:

undefined method `foo' for #<User id: nil, first_name: nil, last_name: nil, admin: nil, last_seen_at: nil, time_zone: nil, phone: nil, temp_role: nil, created_at: nil, updated_at: nil, email: "">

I understand why the error is happening; because there's no foo attribute on the User model.

But I'd still like to pass the foo variable through to the controller. What's the best way of doing that (assuming there is a way)?

CodePudding user response:

There is a way to do it without editing the model and that may be handy if this parameter is not really a part of the model.

You can just add plain tags inside the form_for like this:

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>

<h2>Sign up</h2
  
  <%= f.label :first_name %>
  <%= f.text_field :first_name %>

  <%= label_tag :foo %>
  <%= text_field_tag :foo %>

  <%= f.submit "Sign up" %>

<%= render "devise/shared/links" %>
<% end %>

In this case parameter foo will be outside of user hash, so params will be like

{"user"=> ["first_name"=> "Bob"], "foo"=>"bar"...}
  • Related