class Post < ActiveRecord::Base
belongs_to :user
end
class ExtraPost < Post
belongs_to :user, optional: true
end
导轨 6.1
创建ExtraPost类的实例时,出现用户不能缺席的错误。请告诉我 Rails 是否不支持这种覆盖关联的方式。
不幸的是,我在网上找不到具体的答案。
在您的 Post 模型中,像这样设置您的
belongs_to
:
class Post < ApplicationRecord
belongs_to :employee, optional: true
validates_presence_of :employee, if: Proc.new { self.instance_of?(self.class.base_class) }
...
然后删除
ExtraPost模型中的
belongs_to
。 (它会自动继承父类。)
这样,Post的任何子类,例如ExtraPost,都可以保存,而不需要相关的employee。
这里的问题是
belongs_to
关联宏默认添加验证,并且在子类中重新定义关联并不会删除验证。
相反,您可以手动定义验证并添加可以在子类中覆盖的
if:
条件。
class Post < ActiveRecord::Base
belongs_to :user, optional: true
validates_presence_of :user, if: :user_required?
private
def user_required?
true
end
end
class ExtraPost < Post
def user_required?
true
end
end