【发布时间】:2018-10-24 19:38:26
【问题描述】:
从 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
当我试图推动用户保留 OR 事件时:
@event.users << current_user
我遇到了那个错误:
ActiveRecord::RecordInvalid (Validation failed: Reserve must exist):
为什么验证需要预留?很明显 Reserve 是可选的。
【问题讨论】:
-
也显示您的
Subscription模型。 -
保留是可选的并不明显。 rails 应该怎么知道呢?您需要明确声明它是可选的:
has_one :reserve, optional: true -
has_one :model, optional: true不是 rails 5.2 中的有效键,并且....has_one :reserve, validate: false无效。
标签: ruby-on-rails activerecord has-many-through belongs-to ruby-on-rails-5.2