【发布时间】:2015-04-28 22:34:12
【问题描述】:
我在第一次体验 Rails / Web 开发方面已经有几周的时间了,但遇到了一个我似乎无法在溢出或锻炼中找到的障碍。我觉得我快到了,但还不完全……
我正在为一家慈善机构开发员工网站,并且需要对新员工进行分类,以便为每个员工分配权限。目前,我有一个创建新员工的员工新视图,并有一个嵌套表单用于在其中输入以同时添加员工的部门。但是,目前为每个新员工生成一个新部门。因此,如果我创建了 2 个部门为“Admin”的员工,我最终会得到 2 个具有不同 type_id 的 Admin 部门,而不是将它们分配给相同的部门。假设部门已经存在,我如何在表单中创建员工的类型/部门时分配它。在控制台中我可以这样做:
s = Staff.create(staff_name: "John", staff_email: "John@example.com", password: "asdsadsad")
t = Type.create(department: "Admin")
s.types << t
到目前为止,我的人员和类型(类别)模型看起来像这样(删除了不相关的部分),我在其中添加了accepts_nested_attributes_for:
class Staff < ActiveRecord::Base
has_many :staff_types
has_many :types, through: :staff_types
accepts_nested_attributes_for :types
validates :staff_name, presence: true, length: { minimum: 5, maximum: 50}
has_secure_password
end
class StaffType < ActiveRecord::Base
belongs_to :staff
belongs_to :type
end
class Type < ActiveRecord::Base
validates :department, presence: true, length: { minimum: 2, maximum: 25 }
has_many :staff_types
has_many :staffs, through: :staff_types
end
我已将类型变量列入白名单的人员控制器如下:
class StaffsController < ApplicationController
before_action :set_staff, only: [:edit, :update, :show]
def new
@staff = Staff.new
1.times { @staff.types.build}
end
def create
@staff = Staff.new(staff_params)
if @staff.save
flash[:success] = "Your account has been created successfully"
redirect_to staff_path(@staff)
else
render 'new'
end
end
private
def staff_params
params.require(:staff).permit(:staff_name, :staff_email, types_attributes: [:id, :department])
end
end
最后我的观点如下,我在 form_for 助手中嵌入了嵌套表单:
<div class="row">
<div class="well col-md-8 col-md-offset-2">
<%= form_for @staff do |f| %>
<%= f.label :staff_name %>
<%= f.text_field :staff_name %>
<%= f.label :staff_email %>
<%= f.email_field :staff_email %>
<%= f.label :password %>
<%= f.password_field :password %>
<%= f.label :password_confirmation %>
<%= f.password_field :password_confirmation %>
<%= f.fields_for :types, @staff.types do |types_form| %>
<%= types_form.label :department %>
<%= types_form.text_field :department %>
<% end %>
<%= f.submit(@staff.new_record? ? "Submit Profile" : "Submit Edited Profile", class: "btn btn-success") %>
<% end %>
</div>
</div>
【问题讨论】:
标签: ruby-on-rails forms ruby-on-rails-4 nested many-to-many