Search code examples
ruby-on-railsactiverecordhas-many-throughbelongs-toruby-on-rails-5.2

Unable to push object to model with associations


After upgrading to Rails 5.2 from Rails 4, I've got some issues with model associations.

I have a model Event that has users as a members of event, and each Event has one Reserve for users that want to attend later.

# app/models/event.rb
class Event < ApplicationRecord

  # Events has many Users through subcsriptions
  has_many :subscriptions
  has_one :reserve
  has_many :users, :through => :subscriptions

  ...

end

Reserve model:

# app/models/reserve.rb
class Reserve < ApplicationRecord
  belongs_to :event, optional: true
  has_many :subscriptions
  has_many :users, :through => :subscriptions
end

Subscription model:

class Subscription < ApplicationRecord
  belongs_to :event
  belongs_to :reserve
  belongs_to :user
end

When I'm trying to push user to reserve OR event:

@event.users << current_user

i've got that error:

ActiveRecord::RecordInvalid (Validation failed: Reserve must exist):

Why Reserve is required for validation? It's obvious that Reserve IS optional.


Solution

  • ActiveRecord::RecordInvalid (Validation failed: Reserve must exist)

    You can use optional: true in the belongs_to like below to avoid the error.

    class Subscription < ApplicationRecord
      belongs_to :event
      belongs_to :reserve, optional: true
      belongs_to :user
    end