Skip to content

Allow default to be configured for serialization - #40545

Merged
kamipo merged 1 commit into
rails:masterfrom
alpaca-tc:serialize_default
Nov 5, 2020
Merged

kamipo merged 1 commit into
rails:masterfrom
alpaca-tc:serialize_default

Conversation

@alpaca-tc

Copy link
Copy Markdown
Contributor

Set the default value in the application layer for columns that can't have a default value, like MySQL's text columns.

class Audit < ActiveRecord::Base
  serialize :content, JSON, default: []
end

Audit.new.content #=> []

Comment on lines 44 to 52

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you also add a test for serialize on custom attribute with default?

  def test_serialized_attribute_on_custom_attribute_with_default
    klass = Class.new(ActiveRecord::Base) do
      self.table_name = Topic.table_name
      attribute :content, default: { key: "value" }
      serialize :content, Hash
    end

    t = klass.new
    assert_equal({ key: "value" }, t.content)
  end

We've discussed about fixing the regression 8f2decd, and have agreed that allowing default to be configured with serialize is also useful, similar to #39820.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just added 👍

```ruby
class Audit < ActiveRecord::Base
  serialize :content, JSON, default: []
end

Audit.new.content #=> []
```
@kamipo
kamipo merged commit 6d40c1d into rails:master Nov 5, 2020
kamipo added a commit that referenced this pull request Nov 5, 2020
Allow default to be configured for serialization
@alpaca-tc
alpaca-tc deleted the serialize_default branch November 5, 2020 11:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants