用设计用户创建员工 [英] Creating employee with devise user
问题描述
看起来像这样
用于Devise用户的配置文件模型?
,但我的有所不同。
It looks like this Profile model for Devise users? but mine is different.
我想创建员工记录,该员工可以选择是否拥有用户帐户。我正在为用户使用devise gem。
I want to create employee record and this employee have an option to have a user account or not. I am using devise gem for my user.
所以我有
has_one :user
accepts_nested_attributes_for :user
和用户模型
belongs_to :employee
我知道我需要在用户视图中放置嵌套用户,但是如何将其保存在控制器中?
I know that I need to put nested user in my view, But how to save it in controller?
不是这样的吧?
params.require(:employee).permit(:name, user_attributes: [:email, :password])
您能给我一些提示或有用的链接吗?很难修改设计。谢谢^ _ ^
Can you give some hint or some useful link I can follow? It is hard to modify the devise. Thank you ^_^
推荐答案
Devise 不应被修改;它只是一系列的控制器和一个模型。
Devise shouldn't be modified; it's just a series of controllers and a model.
如果您要创建雇员
,然后将数据传递给 User
模型,您已经采用了正确的方法。
If you want to create an employee
, and then pass data through to the User
model, you've taken the right approach.
您需要做的是保持惯例(例如,构建 User
模型等)以确保维护Devise的功能:
What you'll need to do is keep to convention (IE build the User
model etc) to ensure the functionality of Devise is maintained:
#app/controllers/employees_controller.rb
class EmployeesController < ApplicationController
def new
@employee = Employee.new
@employee.build_user
end
def create
@employee = Employee.new employee_params
@employee.save
end
private
def employee_params
params.require(:employee).permit(:name, user_attributes: [:email, :password, :password_confirmation])
end
end
现在,唯一的问题是 user_attributes
可能是错误的,因为Devise因其强大的参数而挑剔。
Now, the only problem with this is that user_attributes
may be false, as Devise is famously finicky with its strong params.
-
要使表格生效,您可以使用以下命令:
To get the form to work, you'll be able to use the following:
#app/views/employees/new.html.erb
<%= form_for @employee do |f| %>
<%= f.text_field :name %>
<%= f.fields_for :user do |user| %>
<%= user.email_field :email %>
<%= user.password_field :password %>
<%= user.password_field :password_confirmation %>
<% end %>
<%= f.submit %>
<% end %>
我没有任何理由或测试来证明这一点。 甚至还可以降级建议,您可以使用 User.new
调用加载表单。因此,我想您会遇到的主要障碍是强大参数的传递。
I don't have any reason - or tests - to disprove this. Devise even suggests that you can load forms using the User.new
invocation. Thus, I'd surmise that the main hurdle you'll have is the passing of the strong params.
这篇关于用设计用户创建员工的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!