How to add a hidden field to form_with?

2.9k Views Asked by At

I am attempting to add a hidden field to a form_with.

Here are 3 attempts (and results / error messages)

First attempt

From: https://guides.rubyonrails.org/form_helpers.html

<%= hidden_field_tag(:parent_id, "5") %>

So I try:

<%= form_with(model: @message, method: :post) do |f| %> 
<%= f.label :body %> 
<%= f.text_area :body %> 
<%= f.hidden_field_tag :user_id, current_user.id %>
<%= f.submit "Send", class: "btn btn-primary" %>
<% end %>

enter image description here

Second attempt

From: https://api.rubyonrails.org/v6.0.3/classes/ActionView/Helpers/FormHelper.html#method-i-hidden_field

Example: hidden_field(:signup, :pass_confirm)

So I try

<%= f.label :body %> 
<%= f.text_area :body %> 
<%= f.hidden_field :user_id, current_user.id %>
<%= f.submit "Send", class: "btn btn-primary" %>
<% end %>

but

enter image description here

Third attempt

This gets further than the other two attempts, because at least the show view loads rather than erroring.

<%= form_with(model: @message, method: :post) do |f| %> 
<%= f.label :body %> 
<%= f.text_area :body %> 
<%= f.hidden_field user_id: current_user.id %>
<%= f.submit "Send", class: "btn btn-primary" %>
<% end %>

But the parameter that gets submitted is

Unpermitted parameter: :{:user_id=>21}

i.e. it contains some extra punctuation that it shouldn't contain (I think it's been made into a nested hash or something?)

2

There are 2 best solutions below

0
On

Here's what worked <%= f.hidden_field :user_id, value: current_user.id %>

i.e.

<%= form_with(model: @message, method: :post) do |f| %> 
<%= f.label :body %> 
<%= f.text_area :body %> 
<%= f.hidden_field :user_id, value: current_user.id %>
<%= f.submit "Send", class: "btn btn-primary" %>
<% end %>

Where

  • :user_id is the name of the parameter (change to your parameter name)
  • value: is simply telling form_with the value is coming next (i.e. don't change that)
  • current_user.id is the actual value (change to your value)

Based on this answer

0
On

You have some error syntax. If you want to pass value to hidden field by using the :value parameter.

<%= f.hidden_field :user_id, :value => current_user.id %>