我正在尝试使用 form_for 辅助方法在 Rails 中创建新记录。我认为 params 哈希是空白的,因为我在提交表单时不断收到空白错误。
这是我的表格:
<% provide(:title, "Add Department") %>
<h1>Add Department</h1>
<div class="row">
<div class="span6 offset3">
<%= form_for(@department) do |f| %>
<%= render 'shared/department_error_messages' %>
<%= f.label :Full_Department_Title %>
<%= f.text_field :full_name %>
<%= f.label :Department_Abbreviation %>
<%= f.text_field :abbreviation %>
<%= f.submit "Add department", class: "btn btn-large btn-primary" %>
<% end %>
</div>
</div>
这是我的部门控制器
class DepartmentsController < ApplicationController
def show
@department = Department.find(params[:id])
end
def new
@department = Department.new
end
def create
@department = Department.new(params[department_params]) # Not the final implementation!
if @department.save
redirect_to root_path
else
render 'new'
end
end
private
def department_params
# This says that params[:department] is required, but inside that, only params[:department][:full_name] and
# params[:department][:abbreviation] are permitted. Unpermitted params will be stripped out
params.require(:department).permit(:full_name, :abbreviation)
end
end
这是模型:
class Department < ActiveRecord::Base
validates :full_name, presence: true, length: { minimum: 6 }
end
当我提交时,会出现错误,提示 full_name 不能为空(并且字段现在为空)。调试信息是:
--- !ruby/hash:ActionController::Parameters utf8: ✓
authenticity_token: EjfYjWAzaw7YqVZAkCPZwiEMFfb2YLIRrHbH1CpZOwA=
department: !ruby/hash:ActionController::Parameters
full_name: Sports Department
abbreviation: SD
commit: Add department
action: create
controller: departments
我还检查了开发日志。事务开始,然后回滚。我可以在控制台中保存一条记录,所以我猜测它与 params 哈希有关,但无法弄清楚。请帮忙