通过Devise_Invitable发送邀请时,向用户添加属性

时间:2016-10-19 20:25:08

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

当我们通过devise_invitble(当发送初始邀请时)创建帐户时,我陷入困境并且不确定如何向用户添加“account_id”。

基本工作流程是所有者创建帐户,然后帐户所有者可以邀请某人使用应用程序设计可邀请。我需要跟踪用户与帐户的关联,因为帐户只有基于计划类型的“x”个用户。

class InvitationsController < Devise::InvitationsController

  after_action :update_user_account, :only => [:create]


  def update_user_account
    @user = User.find_by_email(params[:user][:email])
    @user.update_attributes(:account_id => current_account.id )
  end

end

这就是我现在正在使用的,但是当我在rails控制台中将该用户拉出来并在服务器输出中查看它时,用户account_id仍为零。

这是帐户模型:

class Account < ApplicationRecord
  include ImageUploader[:image]
  # Constants
  RESTRICTED_SUBDOMAINS = %w(www patrolvault admin test type taurenapplabs taurenmaterialservices)

  # Before Actions
  before_validation :downcase_subdomain

  # Relationships
  belongs_to :owner, class_name: 'User', optional: true
  accepts_nested_attributes_for :owner
  has_many :users

  # Validations
  validates :owner, presence: true

  validates :subdomain, presence: true,
                        uniqueness: { case_sensitive: false },
                        format: { with: /\A[\w\-]+\Z/i, message: 'Contains invalid characters.' },
                        exclusion: { in: RESTRICTED_SUBDOMAINS, message: 'Restricted domain name'}

  has_one :plan
  accepts_nested_attributes_for :plan

  private

  def downcase_subdomain
    self.subdomain = self.subdomain.downcase
  end

end

这是用户模型:

class User < ApplicationRecord
  # Constants & Enums
  USER_LIMITS = ActiveSupport::HashWithIndifferentAccess.new(
    #Plan Name      #Auth Users
    responder:        6,
    first_responder:  12,
    patrol_pro:       30,
    guardian:         60
  )

  # Before Actions

  # Devise Modules
  devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable, :invitable, :lockable, :timeoutable

  # Relationships
  belongs_to :account, optional: true

  # Validations
  validates :f_name, presence: true
  validates :l_name, presence: true
  validates :date_of_birth, presence: true

  #validate :must_be_below_user_limit

  # Custom Methods
  def full_name
    l_name.upcase + ", " + f_name
  end

end

拜托,非常感谢这里的任何帮助!这真的让我很伤心。

2 个答案:

答案 0 :(得分:2)

@user.update_attributes(:account_id => current_account.id )失败,因为User模型上的验证未通过。解决此问题的一种方法是使用update_all更新用户记录,这是一种仅绕过验证的SQL方法:

def update_user_account
  User.where(email: params[:user][:email]).update_all(account_id: current_account.id)
end

答案 1 :(得分:1)

或更少的代码:

def create
  super
  User.where(email: params[:user][:email]).update_all(account_id: current_user.account.id)
end