8

例如,当我转到 时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 of​​ a validation)。

如何在发送邀请之前设置这些字段并让它们在接受邀请时保留并保存?谢谢!

4

1 回答 1

2

导轨 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? }
于 2017-11-20T18:39:34.947 回答