【问题标题】:How can I invite users (using devise_invitable) and populate additional fields during the invite process?如何在邀请过程中邀请用户(使用 devise_invitable)并填充其他字段?
【发布时间】:2015-03-20 18:58:17
【问题描述】:

例如,当我转到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)。

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

【问题讨论】:

  • 嗨。你找到解决方案了吗?我遇到了同样的问题。谢谢
  • 不,抱歉。我最终只是在这个过程的后期设置了它们

标签: ruby-on-rails ruby devise devise-invitable


【解决方案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? }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多