Reputation: 345
I am stuck on a problem related to validation. However, validation errors are present only in production environment and do not make sense.
Details: upon submitting a form via AJAX creating a new stop
instance, I get back Stop#new due to failure of @stop.save in Stop#create action. Errors that are preventing stop saving are caused by
Setup
(Setup Must Exist) - stop belongs_to
Setup, but
there is no validation rule checking for presence of parent setupUser ended
(User Ended Must Exist) - stop belongs_to
user_ended, but again there is no validation rule to enforce user_ended presenceI am not able to replicate same errors in development env, in which app is accepting new stop without validation errors.
Anybody can point me to possible reasons of this? I am trying to think of something to debug in production environment, and any suggestion on this are also welcome.
Upvotes: 2
Views: 420
Reputation: 2255
I did an incremental upgrade from Rails 4.2 to Rails 5.1.4 and also had this issue of the development environment not picking up the require in the belongs_to
associations by default (although the production environment did). Looking at the initializer files, I realized I hadn't gone through the config/initializers/new_framework_defaults.rb
and flipped the new defaults per the suggestion in the file. The belongs_to_required_by_default
flag was set to false in this file. Flipping this flag to true (or removing the file altogether as it was no longer needed) solved this problem, and my development environment now required the belongs_to
associations. However, I'm still unclear why the production environment was not respecting the flag set to false.
Upvotes: 1
Reputation: 345
I searched release notes and discovered that in rails 5.0
belongs_to
will now trigger a validation error by default if the association is not present. You can turn this off on a per-association basis withoptional: true
. Also deprecaterequired
option in favor of optional forbelongs_to
.
Additionally, rake task for updating to version 5.0 of rails is adding the following option
# Require
belongs_to
associations by default. Previous versions had false.Rails.application.config.active_record.belongs_to_required_by_default = false
However, rails 5.1 stopped to use this option without any warning, Rails team decided that documenting this change only in the docs of belongs_to
association should be enough. More in the issue #18937
Upvotes: 0
Reputation: 4216
Well, maybe you are using Rails 5, if thats is the case all belongs_to
associations are required by default. To opt-out of this you should declare it like this:
belongs_to :setup, optional: true
belongs_to :user_ended, optional: true
Upvotes: 2