我對何時使用隱藏字段感到困惑。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 –