Rails Optional Belongs_To

Rails optional belongs_to

Do you have a validation that requires user be present? If so, remove that.

How do I make my belongs_to field optional?

It used to be that you could just leave the value as nil and Rails was perfectly happy. However this was changed in Rails 5.

If you want the belongs_to to be optional, you simply have to pass optional: true:

belongs_to :grading_rubric, optional: true

You can find more info about it here

rails belongs_to optional but check exists if passed

Unfortunately, with optional option it turns off presence validation for your record, but you can add custom validation in your model:

class User < ActiveRecord::Base
belongs_to :team, optional: true

validates_presence_of :team, if: :team_id_present?

private

def team_id_present?
team_id.present?
end
end

How do you declare an optional condition for an ActiveRecord belongs_to association?

It looks like providing a lambda to the optional option won't work (although I haven't tried it). I looked at the source code and this is how optional is used.

required = !reflection.options[:optional]

If required, Rails just adds a presence validation like this:

model.validates_presence_of reflection.name, message: :required

I believe you could go the custom route with something like this:

class Member < ApplicationRecord
belongs_to :group, optional: true
validates :group, presence: true, on: :update
end

Should you use belongs_to if belonging to the object is optional?

Unless you put something like following validation at your post, it won't throw an error:

validates :category, presence: true # it ensures that category must be present

simply the category_id will be nil at that post entity where category is not present, there is nothing wrong about it. If there were 10s and 100s of redundant columns then I think it would be better to go for database normalization.

Configuration to allow optional belongs_to association not working in rail 6

Looking at the new framework defaults file for Rails 5, it had the following

# config/initializers/new_framework_defaults.rb
# Require `belongs_to` associations by default. Previous versions had false.
Rails.application.config.active_record.belongs_to_required_by_default = true

So it appears that the option has been removed completely for Rails 6. So you will need to do it on a case by case basis by adding optional: true. In my case, in most cases, I ended rewriting the code so that the association was required.



Related Topics



Leave a reply



Submit