2012-12-31 34 views
2

我正在使用devise_invitable來允許用戶彼此邀請。我想在創建邀請或接受邀請時爲用戶設置值。一種方法是在這裏不要使用devise_invitable收到回叫

Using devise_invitable for adding Users to a Group in Ruby on Rails?

但這似乎矯枉過正。回調看起來像是一個完美的解決方案,但在我的Rspec測試期間它們似乎並沒有被觸發。

下面是用戶模型:

class User < ActiveRecord::Base 
    belongs_to :company 

    rolify 
    # Include default devise modules. Others available are: 
    # :token_authenticatable, :confirmable, 
    # :lockable, :timeoutable and :omniauthable 
    devise :invitable, :database_authenticatable, :registerable, :confirmable, 
     :recoverable, :rememberable, :trackable, :validatable 

    # Setup accessible (or protected) attributes for your model 
    attr_accessible :role_ids, :as => :admin 
    attr_accessible :name, :email, :password, :password_confirmation, :remember_me, :company 
    validates :company, :presence => true 

    after_invitation_accepted :email_invited_by 
    before_invitation_accepted :email_invited_by 

    private 

    def email_invited_by 
     # This is NEVER executed during tests, even when an invite is successfully accepted 
     puts "Callback worked" 
    end 

end 

約在何處尋找任何線索,將不勝感激。我發現devise_invitable文檔有點不透明。

謝謝!

回答

0

如果用戶真的被邀請(即對象被持久化並且存在邀請令牌集)並且對象(用戶的對象)沒有驗證錯誤,則會觸發devise_invitable回調。這就是說,我看到你在沒有任何條件的情況下驗證company的存在,我認爲這可能會導致驗證錯誤。

如果是這樣的話,你可以添加一個條件這樣

validates :company, :presence => true, :if => Proc.new { self.invitation_token.nil? } 

,這樣就不會導致驗證錯誤並觸發回調。

+0

感謝您的想法,但我不想我不認爲是這樣。我完全評論了驗證,仍然沒有開火! – SimonB666

+0

在Rails控制檯中,'user.invited_to_sign_up?'和'user.valid?'的輸出是什麼,因爲'user'是一個不被接受的用戶對象? –

+0

艾哈邁德,我剛剛發現,當我通過瀏覽器進行邀請時,回調觸發,但不是來自我用於測試的RSPEC腳本。所以問題在別處。謝謝!您的回答非常有幫助! – SimonB666

0

對於那些仍然在尋找答案,這是什麼對我有用。

問題不在於與驗證,因爲在devise_invitable有一個配置驗證的邀請,並默認爲false

# Flag that force a record to be valid before being actually invited 
# Default: false 
# config.validate_on_invite = true 

所以我的解決方案是使用由devise_invitable提供的回調:

after_invitation_accepted :create_profile 

請注意,這需要低於devise :invitable