[Suggestion] Allow proc in belongs_to's optional flag

Hi there,

What about allowing to pass a proc to belongs_to’s optional flag?

So instead of the following:

class Transaction < ApplicationRecord

belongs_to :category, optional: true

validates :category, presence: { message: :required }, if: :auto_created?

end

We could write:

class Transaction < ApplicationRecord

belongs_to :category, optional: ->(record) { record.auto_created? }

end

I’m happy to submit a PR if you agree with the suggestion.

Cheers,

Lucas.

Hi all,

Any thoughts on this?

Lucas Caton

@lucascaton | lucascaton.com.br

I believe this make belongs_to too complex and open a precedent to people want to customize the validation in other ways using the belongs_to syntax. The required validation is just a convenience. It is a good default but sometimes people want more than the default. In those cases they should be explicitly defining their own validation as your example.

Thanks Rafael, good point.

However, the problem by using the code I sent is the inconsistency:

in the first line it contains optional while the second contains a presence validation.

Cheers,