我有:
我想要的是有可能修改学生的个人资料,例如改变其教师和证书。我发现accepts_nested_attributes_for可以帮助我。这就是我所拥有的:
class User < ActiveRecord::Base
has_one :student
has_one :header
has_one :admin
has_many :progresses, :through => :student
accepts_nested_attributes_for :student
end
class Student < ActiveRecord::Base
belongs_to :user
belongs_to :group
has_one :specialization, through: :group
has_many :progresses
scope :activated, lambda {(where("users.activated = 'off'"))}
self.per_page = 1
end
class Admin::StudentsController < AdminController
before_action :set_user, only: [:show, :edit, :update, :destroy]
def index
@students = Student.joins(:user).joins(:group).paginate(:page => params[:page]).all
end
def show
end
def edit
end
def update
end
private
def set_user
@student = Student.find(params[:id])
@student.build_user
end
end
表格部分
= form_for([:admin,@student]) do |f|
- if @student.errors.any?
#error_explanation
h2
= pluralize(@student.errors.count, "error")
| prohibited this group from being saved:
ul
- @student.errors.full_messages.each do |msg|
li= msg
.field
= f.fields_for :user do |builder|
= builder.label :first_name
br/
= builder.text_field :first_name
.field
= f.label :faculty_id
br/
= f.text_field :faculty_id
.actions
= f.submit
我在浏览器中查看了inspect元素,用户对象的输入是
<input id="student_user_first_name" name="student[user][first_name]" type="text">
这似乎是正确的。但这个领域是空的。请告诉我哪里出错了?谢谢。
答案 0 :(得分:0)
Rails 4使用强参数,因此您需要将控制器中的参数列入白名单。这是一个很好的解释,它考虑了accepts_nested_attribute_for的使用。 http://edgeapi.rubyonrails.org/classes/ActionController/StrongParameters.html