覆盖子类中的belongs_to关联

问题描述 投票:0回答:2
class Post < ActiveRecord::Base
  belongs_to :user
end

class ExtraPost < Post
  belongs_to :user, optional: true
end

导轨 6.1

创建ExtraPost类的实例时,出现用户不能缺席的错误。请告诉我 Rails 是否不支持这种覆盖关联的方式。

不幸的是,我在网上找不到具体的答案。

ruby-on-rails ruby-on-rails-6
2个回答
1
投票

在您的 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


0
投票

这里的问题是

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
© www.soinside.com 2019 - 2024. All rights reserved.