Skip to content

Allow attribute's default to be configured but keeping its own type - #39830

Merged
kamipo merged 1 commit into
rails:masterfrom
kamipo:lazy_construct_attribute_type_2
Jul 13, 2020
Merged

kamipo merged 1 commit into
rails:masterfrom
kamipo:lazy_construct_attribute_type_2

Conversation

@kamipo

@kamipo kamipo commented Jul 13, 2020

Copy link
Copy Markdown
Member
class Post < ActiveRecord::Base
  attribute :written_at, defaullt: -> { Time.now.utc }
end

# Rails 6.0
Post.type_for_attribute(:written_at) # => #<Type::Value ... precision: nil, ...>

# Rails 6.1
Post.type_for_attribute(:written_at) # => #<Type::DateTime ... precision: 6, ...>

This is an alternative of #39797.

Context #39797 (comment).

If people intend to override the existing type on the attribute, usually
an overriding type is explicitly specified, so I agree that the current
behavior (drop existing type information if type is omitted) is
practically quite useless, and it is almost like a bug in that there is
no way to override just the default.

So I'd like to change the current behavior on existing attributes
without a deprecation as a fix.

Closes #39797.

See also kufu/activerecord-bitemporal#57.

Comment thread activerecord/CHANGELOG.md Outdated

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.

Suggested change
attribute :written_at, defaullt: -> { Time.now.utc }
attribute :written_at, default: -> { Time.now.utc }

```ruby
class Post < ActiveRecord::Base
  attribute :written_at, default: -> { Time.now.utc }
end

# Rails 6.0
Post.type_for_attribute(:written_at) # => #<Type::Value ... precision: nil, ...>

# Rails 6.1
Post.type_for_attribute(:written_at) # => #<Type::DateTime ... precision: 6, ...>
```

This is an alternative of rails#39797.

Context rails#39797 (comment).

If people intend to override the existing type on the attribute, usually
an overriding type is explicitly specified, so I agree that the current
behavior (drop existing type information if type is omitted) is
practically quite useless, and it is almost like a bug in that there is
no way to override just the default.

So I'd like to change the current behavior on existing attributes
without a deprecation as a fix.

Closes rails#39797.

See also kufu/activerecord-bitemporal#57.
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