我很难弄清楚如何将用户分配到某个部门 我阅读了很多论坛,似乎无法做任何事情。以下是我的模特
# organization.rb
has_many :departments
# department.db
belongs_to :organization
has_many :employees
has_many :users, through: :employees
# employee.rb
belongs_to :department
belongs_to :user
# user.rb
devise :database_authenticatable, :registerable, :recoverable,
:rememberable, :trackable, :validatable
has_many :employees
has_many :departments, through: :employees
# routes.rb
root "static_pages#index"
resources :organizations, except: :index do
get 'departments/:id/signup', to: 'departments#department_sign_up'
resources :departments do
resources :employees, except: :index, shallow: true
end
end
我想要完成的是在department#show
页面上添加表单或链接以添加用户。
因此,在创建用户时,它将在employees表中创建一条记录,用于将用户链接到部门。我不知道从哪里开始。我最初的兴趣是使用电子邮件,密码, password_confirmation form_for [@department, @employee]并为fields_for
个用户设置嵌套属性>属性?
非常感谢任何帮助,谢谢。
答案 0 :(得分:1)
实现此目标的简单方法是创建user
并移交department_id
。因此,我建议为create_employee
创建一个自己的路由来分离逻辑(当然,你可以通过添加一个新的控制器来开始分离,只是为了创建新的部门员工,例如已经嵌套在部门资源下以避免使用隐藏字段)。
但我只是想给你一个提示:
# in department#show
= form_for(User.new, url: create_employee_path(
= f.hidden_field :department_id
____________________
# in routes.rb
resources :users do
post 'create_employee', on: :collection
end
然后在users_controller.rb
中,您可以按以下顺序创建这些对象:
params[:user]
哈希department_id
e.g。像这样:
# users_controller.rb
...
def create_emlpoyee
@department = Department.find(:department_id)
@user = User.create(params[:user])
# here you will want to check if the creation was successful
...
if @user && @department
Employee.create(user: @user, department: @department)
end
# here you can redirect to wherever you want
redirect_to @user
end
这个代码当然可以改进,但它应该向您展示方法。
我希望这能帮助你完成任务。