class RuboCop::Cop::Rails::BelongsTo
end
belongs_to :blog, optional: false
class Post < ApplicationRecord
# good
end
belongs_to :blog, required: true
class Post < ApplicationRecord
# bad
end
belongs_to :blog, optional: true
class Post < ApplicationRecord
# good
end
belongs_to :blog, required: false
class Post < ApplicationRecord
# bad
@example
user can remove depending on their defaults.
‘required: true`, we’ll simply invert it to ‘optional: false` and the
superfluous `optional: false`). Therefore, in the cases we’re using
should replace it with ‘optional: false` (or, similarly, remove a
can’t say whether it’s safe to remove ‘required: true` or whether we
value of `config.active_record.belongs_to_required_by_default`, we
However, without knowing whether they’ve set overridden the default
definitely want to autocorrect to ‘optional: true`.
In the case that the developer is doing `required: false`, we
option in favor of optional for belongs_to. (Pull Request)
per-association basis with optional: true. Also deprecate required
association is not present. You can turn this off on a
belongs_to will now trigger a validation error by default if the
From the release notes:
can be controlled through the use of `optional: true`.
Since Rails 5, belongs_to associations are required by default and this
association is required via the deprecated `required` option instead.
Looks for belongs_to associations where we control whether the
def on_send(node)
def on_send(node) match_belongs_to_with_options(node) do |option_node, option_value| message, replacement = if option_value.true_type? [SUPERFLOUS_REQUIRE_TRUE_MSG, 'optional: false'] elsif option_value.false_type? [SUPERFLOUS_REQUIRE_FALSE_MSG, 'optional: true'] end add_offense(node.loc.selector, message: message) do |corrector| corrector.replace(option_node, replacement) end end end