嵌套表单和强参数——rails 4



我有一个表单和强参数的问题。我看到很多人在我之前就有这样的问题,但没有任何建议对他们有效。

我的形式:

<%= 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的输出为:

{"school_id"=>"234234","手机"=>"234234234","attendance_officer_id"=>"8","attendance_officer_type"=>"用户","language_preferred"=> "

我一直在尝试student_params的每种不同格式,我可以在论坛上找到,并得出结论,问题必须在其他地方-我是否正确创建表单?我的模型有问题吗?

谢谢你给我的任何帮助。

沃尔特

尝试将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

最新更新