我正在尝试使用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 hash有关,但无法弄明白。请帮忙
答案 0 :(得分:3)
这一行:
@department = Department.new(params[department_params])
应该是:
@department = Department.new(department_params)
而且,作为一个小问题(但不会导致此问题),您的标签标签应如下所示:
f.label :full_name, "Full Department Title"
这样他们就可以正确地与输入相关联。