私の種.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です。
新規および作成時にコンテンツを設定しても機能しないようです。フィールドを設定してから再度保存すると機能します。発生したエラーはありません。