【问题标题】:Rails polymorphic association: Restrict allowed classesRails 多态关联:限制允许的类
【发布时间】:2016-11-18 16:14:18
【问题描述】:

我希望一个类通过多态关联属于其他类。

将关联限制为特定类列表的最佳方法是什么?

我正在考虑使用这样的自定义验证方法,但我不知道这是否真的是最好的主意:

class Feature < ActiveRecord::Base

  belongs_to :featureable, polymorphic: true

  validate :featurable_is_of_allowed_class

  FEATURABLE_CLASSES = ["Country", "City", "Store", "Product"]

  def featurable_is_of_allowed_class
    if !FEATURABLE_CLASSES.include? featurable.class.name
      errors.add(:featurable, "class not allowed for association")
    end
  end

end

【问题讨论】:

  • 如果您希望该类在另一个类具有has_many :features 时抛出错误或某种错误,这是不可能的。

标签: ruby-on-rails validation activerecord polymorphic-associations


【解决方案1】:

我们对多态类型使用了这个验证(Rails 5):

ALLOWED_TYPES = %w(Star Planet).freeze

validates :moonable_type, presence: true, inclusion: { in: ALLOWED_TYPES }

【讨论】:

  • validates :moonable_id, presence: true, numericality: { only_integer: true } 不是必需的,因为 Rails 已经检查了可月球记录是否存在。
  • @PereJoanMartorell 感谢您让我知道!
  • 嗯,关于如何允许 nil 的想法?我猜你会为此做一个自定义验证?
  • @unflores 您可以使用 allow_nil 选项。例如:validates :size, inclusion: { in: ALLOWED_TYPES }, allow_nil: trueRails guide
猜你喜欢
  • 1970-01-01
  • 2018-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多