无法将对象推送到具有关联的模型
Unable to push object to model with associations
从 Rails 4 升级到 Rails 5.2 后,模型关联出现了一些问题。
我有一个模型事件,其中有用户作为事件成员,每个事件都有一个预留给以后想参加的用户。
# 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
储备车型:
# app/models/reserve.rb
class Reserve < ApplicationRecord
belongs_to :event, optional: true
has_many :subscriptions
has_many :users, :through => :subscriptions
end
订阅模式:
class Subscription < ApplicationRecord
belongs_to :event
belongs_to :reserve
belongs_to :user
end
当我试图推动用户预订或事件时:
@event.users << current_user
我遇到了那个错误:
ActiveRecord::RecordInvalid (Validation failed: Reserve must exist):
为什么需要预留验证?很明显 Reserve 是可选的。
ActiveRecord::RecordInvalid (Validation failed: Reserve must exist)
您可以在 belongs_to
中使用 optional: true
来避免错误。
class Subscription < ApplicationRecord
belongs_to :event
belongs_to :reserve, optional: true
belongs_to :user
end
从 Rails 4 升级到 Rails 5.2 后,模型关联出现了一些问题。
我有一个模型事件,其中有用户作为事件成员,每个事件都有一个预留给以后想参加的用户。
# 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
储备车型:
# app/models/reserve.rb
class Reserve < ApplicationRecord
belongs_to :event, optional: true
has_many :subscriptions
has_many :users, :through => :subscriptions
end
订阅模式:
class Subscription < ApplicationRecord
belongs_to :event
belongs_to :reserve
belongs_to :user
end
当我试图推动用户预订或事件时:
@event.users << current_user
我遇到了那个错误:
ActiveRecord::RecordInvalid (Validation failed: Reserve must exist):
为什么需要预留验证?很明显 Reserve 是可选的。
ActiveRecord::RecordInvalid (Validation failed: Reserve must exist)
您可以在 belongs_to
中使用 optional: true
来避免错误。
class Subscription < ApplicationRecord
belongs_to :event
belongs_to :reserve, optional: true
belongs_to :user
end