我对何时使用隐藏字段感到困惑。Rails:隐藏字段的最佳实践
我试图提交表单时传递USER_ID,除了:
<%= f.hidden_field :user_id %>
但是,我知道这是不对的。我已经将模型设置为属于用户,但据我所知,不会自动分配ID。
有人能指出我正确的方向吗?
编辑:谢谢大家的回应。正如我之前所说的,我知道你不应该使用hidden_field来处理像ID这样重要的事情。按照链接@ brad-werth的帖子,批量分配太容易了。
我正在添加代码,以使其更容易回答。我需要提交下面的表格,并确保它已分配给用户。而且,是的,我使用的设计:
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 %>
您能否给您正在使用 – Sajin
喜形式更多详情,欢迎到堆栈溢出。你能否提供一些支持代码,例如控制器动作(既呈现表单又接受提交的值)。你在哪里决定使用哪个用户ID?你可以提供更多的“表格”,以便我们可以看到它是什么形式*为*等 –
http://stackoverflow.com/questions/5163775/is-the-use-of-hidden-fields-in -forms-insecure –