保存对象后attr_encrypted为零

时间:2014-04-28 17:23:53

标签: ruby-on-rails attr-encrypted

我的种子.rb:

  doc = Document.new(
    :name => "Document"+i,
    :description => "Description of Document"+i,
    :content => "hello world",  
    :public => false
  )
  doc.save! #encrypted_content and content will be nil after this line
  doc.content = "hello"
  doc.save!  #encrypted_content will be set correctly after this line

我的文档模型:

class Document < ActiveRecord::Base
  include KeyCreator

  has_many :document_users, dependent: :destroy
  has_many :users, :through => :document_users
  before_create :before_create

  validates :name, presence: true
  validates :description, presence: true

  attr_encrypted :content, key: 'secret'

  def self.admin_in(user)
    Document.joins(:document_users)
     .where(:document_users => {:user => user, :role => ["owner", "admin"]})
     .order(:name)
  end

  def self.non_admin_in(user)
    Document.joins(:document_users)
     .where(:document_users => {:user => user})
     .where.not(:document_users => {:role => ["owner", "admin"]})
     .where.not(:document_users => {invite_accepted_date: nil})
     .order(:name)
  end

  def current_doc_user(current_user)
    self.document_users.find_by(user: current_user)
  end

  def to_param
    "#{link_key}".parameterize
  end

  def after_create(current_user)
    #setting email to avoid validation error
    self.document_users.create!(user: current_user, email: current_user.email, role: "owner")
  end  

    private

  def before_create
    now = DateTime.now
    self.content = nil
    self.api_key = create_key
    self.link_key = create_key
  end

end

我的迁移:

class CreateDocuments < ActiveRecord::Migration

  def change

    create_table :documents do |t|
      t.string :name
      t.text :description
      t.text :encrypted_content   #I also tried t.string. It doesn't work either
      t.boolean :public
      t.string :api_key
      t.string :link_key

      t.timestamps
    end

    add_index :documents, :api_key, unique: true
    add_index :documents, :link_key, unique: true
    #add_index :users, :reset_password_token, unique: true

  end
end

我的环境是rails 4.0.3,ruby 2.1.1。

设置新内容并创建内容似乎无法正常工作。它在我设置字段然后再次保存时有效。没有引发错误。

0 个答案:

没有答案