【发布时间】:2016-05-30 11:01:12
【问题描述】:
一切正常,但我想将 create 操作中的代码更改为 update 操作中的代码。现在,在创建操作中,我正在遍历所有值并保存它们,但想在一行中完成。
我有一个大学模特。
class College< ActiveRecord::Base
has_many :staffs, dependent: :destroy
accepts_nested_attributes_for :staffs, reject_if: :all_blank, allow_destroy: true
end
这是我的 Staff.rb
class Staff < ActiveRecord::Base
belongs_to :college
end
这些是我的 Staffs 控制器 create 和 update 操作
def create
@college= College.find(params[:college][:id_college_profile]
)
staff_params = params[:college][:staffs_attributes].values
staff_params.each do |staff_param|
@staff = @college.staffs.new
@staff.name = staff_param[:name]
@staff.designation = staff_param[:designation]
@staff.experience = staff_param[:experience]
@staff.specialization = staff_param[:specialization]
@staff.save
end
redirect_to dashboard_path(id: @college.id), notice: "Successfully added Staff."
end
def update
@college= College.find(params[:college][:id_college]
)
@college.update_attributes(staff_parameters)
redirect_to root_path
end
这些都是强参数
def staff_parameters
params.require(:college).permit(:id, staffs_attributes: [:id, :name, :specialization, :experience, :designation, :_destroy])
end
有没有一种方法可以在创建操作中保存所有人员,而无需遍历所有值,而是像在更新操作中一样使用一行代码保存所有人员?
我已经在 StaffsController 创建操作中尝试过这个
def create
@college= College.find(params[:college][:id_college]
)
@staff= @college.staffs.new(staff_parameters)
@staff.save
redirect_to dashboard_path(id: @college.id), notice: "Successfully added Staffs."
end
但它抛出了这个错误
unknown attribute 'staffs_attributes' for Staff.
有人可以帮我解决这个问题吗?
【问题讨论】:
标签: ruby-on-rails nested-forms has-many cocoon-gem