2016-10-19 55 views
0

当我的帐户通过devise_invitble(发送初始邀请时)创建时,我坚持并不确定如何将“account_id”添加到用户。当通过Devise_Invitable发送邀请时向用户添加属性

基本工作流程是所有者创建一个帐户,然后该帐户的所有者可以邀请某人使用该应用程序与设计invitable。我需要跟踪用户与帐户关联的情况,因为帐户只有基于计划类型的“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 

这是我在用,现在,但是当我拉在轨控制台用户起来看看它在服务器输出,用户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 

请,这里的任何援助将不胜感激!这真是我的干扰向上。

+0

这听起来像用户记录可由于验证未通过,因此不能保存。你确定用户有一个f_name,l_name和date_of_birth吗? – infused

+0

@infused当我发送邀请时,控制台中唯一填写的字段是电子邮件和所有可邀请的字段,当用户接受邀请时,他们会看到一个字段,允许他们添加他们的姓名和密码,全部这通过并存在于控制台和日志中...唯一没有更新的项目是account_id。 - 添加上面的控制台读数。 –

+0

这是因为@ user.update_attributes(:account_id => current_account.id)由于验证错误而失败。 – infused

回答

1

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

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

这真棒!非常感谢你的帮助!真的很感激它! –

0

或者更少的代码:

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