I'm really confused on when to use hidden fields.
I'm trying to pass the user_id when submitting a form, other than:
<%= f.hidden_field :user_id %>
However, I know this is wrong. I've set the model to belong to user but as far as I can tell, that doesn't auto assign the ID.
Can someone point me in the right direction?
EDIT: Thanks for the responses everyone. As I stated before, I know you shouldn't use hidden_field for something important like ID. Mass assignment is too easy this way, as per the link @brad-werth post.
I'm adding code to make this a little easier to answer. I need to submit the form below and make sure that it's assigned to a user. Also, yes, I'm using Devise:
votes_controller.rb
class VotesController < ApplicationController
before_action :set_vote, only: [:show, :edit, :update, :destroy]
# GET /votes
# GET /votes.json
def index
@votes = Vote.for_user(current_user).where(nil)
end
# GET /votes/1
# GET /votes/1.json
def show
redirect_to action: "index"
end
# GET /votes/new
def new
@vote = Vote.new
if @vote.save
user_id = current_user.id
else
render 'new'
end
end
_form.html.erb
<%= form_for(vote) do |f| %>
<% if vote.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(vote.errors.count, "error") %> prohibited this vote from being saved:</h2>
<ul>
<% vote.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :widget %>
<%= f.text_field :widget_name, data: {autocomplete_source: widgetnames_path} %>
</div>
<div class="">
<!-- description will go here -->
</div>
<div class="field">
<%= f.label :originality %>
<%= f.number_field :originality %>
</div>
<div class="field">
<%= f.label :interest %>
<%= f.number_field :interest %>
</div>
<div class="field">
<%= f.label :rating %>
<%= f.number_field :rating %>
</div>
<div class="field">
<%= f.label :comments %>
<%= f.text_field :comments %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>