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 %>
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
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?)
Here's what worked
<%= f.hidden_field :user_id, value: current_user.id %>
i.e.
Where
:user_id
is the name of the parameter (change to your parameter name)value:
is simply tellingform_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