无法将用户password_salt用于其他模型

时间:2013-12-25 22:21:51

标签: ruby-on-rails model

在我的社区模型中,我想使用attr_encrypted gem加密个人和机密笔记。每个用户都有一个password_salt字段,我想在内容加密中使用该字段。我玩过各种各样的方法,似乎无法找到方法。这不起作用,但它会让你知道我想要做什么:

class Community < ActiveRecord::Base
  attr_accessible :first_name, :last_name, :notes, :user_id
  attr_encrypted :notes, :key => :encryption_key

  def encryption_key
    user = User.find(params[:user_id])
    user.password_salt
  end
end

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

在您的社区模型中,您应该

class Community < ActiveRecord::Base
  belongs_to :user
  attr_encrypted :email, :key => 'a secret key', :attribute => self.user.password_salt

  ....
end

答案 1 :(得分:1)

这很有效。

class Community < ActiveRecord::Base
  belongs_to :user
  attr_accessible :first_name, :last_name, :notes, :user_id
  attr_encrypted :notes, :key => :encryption_key

  def encryption_key
    user = User.find(self.user_id)
    user.password_salt
  end
end