表单和强参数存在问题。我看到很多人已经摆脱了这些问题,但没有任何暗示给他们看起来有效。
我的表格:
<%= form_for(@student) do |f| %>
<%= f.label :school_id %>
<%= f.text_field :school_id, class: 'form-control' %>
...
<%= f.fields_for :enrollments do |enrol_form| %>
<%= enrol_form.label :date , "Enrollment date", class: 'form-control' %>
<%= enrol_form.date_field :date , class: 'form-control' %>
<%= enrol_form.hidden_field :reason, value: "Entered on system" %>
<% end %>
...
<% end %>
型号:
class Student < ActiveRecord::Base
include PhoneValid
has_many :enrollments, inverse_of: :student
validates :enrollments, :presence => { message: "Must have at least one enrollment event" }
accepts_nested_attributes_for :enrollments
end
class Enrollment < ActiveRecord::Base
belongs_to :student
default_scope -> { order(date: :asc) }
validates :date, presence:true
validates :enroll_wd, inclusion: {in: %w(ENROLL WD), messages: "%{value} must be either WD or ENROLL"}
end
控制器:
class StudentsController < ApplicationController
def create
@student = Student.new(student_params)
@student.save
end
def student_params
params.require(:student).permit(:school_id, :cellphone, :attendance_officer_id, :attendance_officer_type, :language_preferred, {enrollment_attributes: [:date, :reason, :id]})
end
end
根据debug(params)
,我的表单输出是:
--- !ruby/hash:ActionController::Parameters
utf8: "✓"
authenticity_token: >cuk8Y+d8fHhJ3mU7wtRYtyDJoiYaG8lfzHvdGVBUI+1qmH7xQr20BHsBAFRT4r1EfDb/MMbxMq8rbKw3Cf2Y1A==
student: !ruby/hash:ActionController::Parameters
school_id: '234234'
cellphone: '234234234'
language_preferred: en
enrollments_attributes: !ruby/hash:ActionController::Parameters
'0': !ruby/hash:ActionController::Parameters
date: '2015-07-10'
reason: Entered on system
attendance_officer_id: '8'
attendance_officer_type: User
commit: Save student
controller: students
action: create
student_params
的输出是:
{&#34; school_id&#34; =&gt;&#34; 234234&#34;,&#34;手机&#34; =&gt;&#34; 234234234&#34;,&#34; attendance_officer_id&# 34; =&gt;&#34; 8&#34;,&#34; attendance_officer_type&#34; =&gt;&#34;用户&#34;,&#34; language_preferred&#34; =&gt;&#34; < / p>
我一直在尝试在论坛中找到的student_params
的每种不同格式,并得出结论,问题必须在其他地方 - 我是否正确创建了表单?我的模特有什么问题吗?
感谢您提供任何帮助。
沃尔特
答案 0 :(得分:1)
尝试将student_params
更改为
def student_params
params.require(:student).permit(:school_id, :cellphone, :attendance_officer_id, :attendance_officer_type, :language_preferred, enrollments_attributes: [:date, :reason, :id])
end