1
0
Fork 0
mirror of https://github.com/paper-trail-gem/paper_trail.git synced 2022-11-09 11:33:19 -05:00

fix rails4 enums attribute issue

With a Rails 4 enum field the changed attributes hash contains the
mapped value and when prev[attr] assigns the value it will be lost.
This commit is contained in:
Greg Molnar 2014-06-12 20:45:32 +01:00
parent 51de996649
commit 348b71e082
4 changed files with 24 additions and 2 deletions

View file

@ -342,9 +342,13 @@ module PaperTrail
all_timestamp_attributes.each do |column| all_timestamp_attributes.each do |column|
previous[column] = send(column) if self.class.column_names.include?(column.to_s) and not send(column).nil? previous[column] = send(column) if self.class.column_names.include?(column.to_s) and not send(column).nil?
end end
enums = previous.respond_to?(:defined_enums) ? previous.defined_enums : {}
previous.tap do |prev| previous.tap do |prev|
prev.id = id # `dup` clears the `id` so we add that back prev.id = id # `dup` clears the `id` so we add that back
changed_attributes.select { |k,v| self.class.column_names.include?(k) }.each { |attr, before| prev[attr] = before } changed_attributes.select { |k,v| self.class.column_names.include?(k) }.each { |attr, before|
before = enums[attr][before] unless enums[attr].nil?
prev[attr] = before
}
end end
end end

View file

@ -0,0 +1,4 @@
class PostWithStatus < ActiveRecord::Base
has_paper_trail
enum status: { draft: 0, published: 1, archived: 2 }
end

View file

@ -92,6 +92,10 @@ class SetUpTestTables < ActiveRecord::Migration
t.string :content t.string :content
end end
create_table :post_with_statuses, :force => true do |t|
t.integer :status
end
create_table :animals, :force => true do |t| create_table :animals, :force => true do |t|
t.string :name t.string :name
t.string :species # single table inheritance column t.string :species # single table inheritance column
@ -100,7 +104,7 @@ class SetUpTestTables < ActiveRecord::Migration
create_table :documents, :force => true do |t| create_table :documents, :force => true do |t|
t.string :name t.string :name
end end
create_table :legacy_widgets, :force => true do |t| create_table :legacy_widgets, :force => true do |t|
t.string :name t.string :name
t.integer :version t.integer :version

View file

@ -1376,6 +1376,16 @@ class HasPaperTrailModelTest < ActiveSupport::TestCase
end end
end end
context 'A record with enum fields' do
should "keep the integer in versions" do
post = PostWithStatus.create!(status: "draft")
assert post.draft?
post.published!
post.archived!
assert post.previous_version.published?
end
end
private private