例如,当我转到users/invitations/new
时,唯一的字段是:email
。我想邀请一位用户,除了提供他们的电子邮件外,还提供:
user belongs_to company
)我创建了Users::InvitationsController < Devise::InvitationsController
:
class Users::InvitationsController < Devise::InvitationsController
private
def resource_params
params.permit(user: [:email, :invitation_token, :role, :company_id])[:user]
end
end
我将这些字段添加到users/invitations/new
。邀请发送正常,但当我接受并输入密码时,我的验证无法说No role is selected
(b / c验证)。
如何在发送邀请之前设置这些字段并将其保留并在接受邀请时保存?谢谢!
答案 0 :(得分:1)
Rails 5
以下是我使用accepts_nested_attributes_for
的解决方案。如果您的自定义属性直接位于用户模型上,则应该能够将profile_attributes: [:first_name, :last_name]
替换为:first_name, :last_name, :role, :company
。
这是我的控制器。
class InvitationsController < Devise::InvitationsController
before_action :update_sanitized_params, only: :update
# PUT /resource/invitation
def update
respond_to do |format|
format.js do
invitation_token = Devise.token_generator.digest(resource_class, :invitation_token, update_resource_params[:invitation_token])
self.resource = resource_class.where(invitation_token: invitation_token).first
resource.skip_password = true
resource.update_attributes update_resource_params.except(:invitation_token)
end
format.html do
super
end
end
end
protected
def update_sanitized_params
devise_parameter_sanitizer.permit(:accept_invitation, keys: [:password, :password_confirmation, :invitation_token, profile_attributes: [:first_name, :last_name]])
end
end
在我的表格中
<%= f.fields_for :profile do |p| %>
<div class="form-group">
<%= p.label :first_name, class: 'sr-only' %>
<%= p.text_field :first_name, autofocus: true, class: 'form-control', placeholder: 'First name' %>
</div>
<div class="form-group">
<%= p.label :last_name, class: 'sr-only' %>
<%= p.text_field :last_name, class: 'form-control', placeholder: 'Last name' %>
</div>
<% end %>
在user.rb中我有
...
accepts_nested_attributes_for :profile, reject_if: proc { |attributes| attributes[:first_name].blank? }