Support custom validation contexts in `required`
This PR proposes to support custom validation contexts to determine whether a field is required or not.
Current Behavior
Given the model:
class User
validates :name, presence: true
validates :avatar, presence: true, on: :with_picture
end
The following currently renders both name and avatar as required:
<%= simple_form_for @user do |f| %>
<%= f.input :name %>
<%= f.input :avatar %>
<% end %>
This does not correspond to the behavior of @user.save, which does not require avatar.
Proposed Solution
This PR proposes a new option context on inputs. Its value is used to determine whether the input is required or not.
The above example would only mark name as required. The following example marks both name and avatar as required.
<%= simple_form_for @user do |f| %>
<%= f.input :name %>
<%= f.input :avatar, context: :with_picture %>
<% end %>
The logic is as follows:
Validation context of validates in the model |
context option of input |
Required |
|---|---|---|
validates presence: true |
context: :with_picture |
required |
validates presence: true, on: :with_picture |
none | optional |
validates presence: true, on: :with_picture |
context: :with_picture |
required |
With the current feature set of simple_form, it is already possible to define the context option for the whole form:
<%= simple_form_for @user, defaults: { context: :with_picture } do |f| %>
<%= f.input :name %>
<%= f.input :avatar %>
<% end %>
This would make working with validation contexts much easier, in my opinion 🙂
Current Workaround
The required option on the input can be used already to control this behavior. However, determining whether there is a presence validator on the context requires extra code, and cannot be set on the whole form easily (cf. https://stackoverflow.com/a/14234720/1023963).