[Suggestion] Allow proc in belongs_to's optional flag

85 views
Skip to first unread message

Lucas Caton

unread,
Feb 1, 2017, 3:39:59 AM2/1/17
to Ruby on Rails: Core
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.

Lucas Caton

unread,
Feb 6, 2017, 7:51:42 PM2/6/17
to rubyonra...@googlegroups.com
Hi all,

Any thoughts on this?

--
You received this message because you are subscribed to a topic in the Google Groups "Ruby on Rails: Core" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/rubyonrails-core/V-padeQT7SQ/unsubscribe.
To unsubscribe from this group and all its topics, send an email to rubyonrails-co...@googlegroups.com.
To post to this group, send email to rubyonra...@googlegroups.com.
Visit this group at https://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.

Rafael Mendonça França

unread,
Feb 7, 2017, 7:41:04 AM2/7/17
to rubyonra...@googlegroups.com
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.

You received this message because you are subscribed to the Google Groups "Ruby on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-co...@googlegroups.com.

Lucas Caton

unread,
Feb 7, 2017, 9:47:51 PM2/7/17
to rubyonra...@googlegroups.com
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,

Reply all
Reply to author
Forward
0 new messages