【发布时间】:2017-03-14 03:56:22
【问题描述】:
我真的很困惑何时使用隐藏字段。
我在提交表单时尝试传递 user_id,除了:
<%= f.hidden_field :user_id %>
但是,我知道这是错误的。我已将模型设置为属于用户,但据我所知,这不会自动分配 ID。
有人能指出正确的方向吗?
编辑:感谢大家的回复。正如我之前所说,我知道您不应该将 hidden_field 用于 ID 之类的重要内容。根据链接@brad-werth 的帖子,这样分配质量太容易了。
我正在添加代码以使这个问题更容易回答。我需要提交下面的表格并确保它已分配给用户。另外,是的,我正在使用 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 %>
【问题讨论】:
-
你能提供更多关于你使用的表格的细节
-
您好,欢迎来到 Stack Overflow。您能否提供一些支持代码,例如控制器操作(呈现表单的操作和接受提交的值的操作)。您在哪里决定要使用哪个用户 ID?你能提供更多的
form,以便我们可以看到它是一个表单for等
标签: ruby-on-rails ruby