【问题标题】:Rails STI validation should have oneRails STI 验证应该有一个
【发布时间】:2013-11-21 20:07:41
【问题描述】:

如何进行(我认为是自定义)验证以确定我的模型应该具有我的任一 STI 模型之一?

我的模型是这样的:

class Account < ActiveRecord::Base
  has_many :users
  has_one :admin, class_name: Admin, dependent: :destroy
  has_many :members, class_name: Member, dependent: :destroy

  accepts_nested_attributes_for :admin, reject_if: proc { |attributes| attributes['name'].blank? }
  accepts_nested_attributes_for :members, reject_if: proc { |attributes| attributes['name'].blank? }

  # Validate should have one of either a member or a user
  # validates :users, ...
end

class User < ActiveRecord::Base
end

class Admin < User
end
class Member < User
end

我想验证,当一个帐户被创建时,它应该有一个管理员或至少一个成员。

如果需要,我可以提供更多信息。

谢谢!

【问题讨论】:

  • 一个帐户在之后创建之前不会有任何用户。需要先保存记录,然后才能将用户链接到它。
  • 哦,我忘了说这已经接受了nested_attributes_for。将编辑问题。

标签: ruby-on-rails validation activerecord ruby-on-rails-4 sti


【解决方案1】:

如果两者都不存在,您可能需要使用自定义验证添加错误。

class Account < ActiveRecord::Base
    validate :require_at_least_one_user

    def require_at_least_one_user
        errors.add(:user, "At least one user is required.") if self.admin.blank? && self.members.blank?
    end
end

【讨论】:

    【解决方案2】:

    我会验证至少一个用户的存在,无论其类型如何。

    也许this 可以提供帮助。

    祝你好运。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-08
      • 1970-01-01
      • 1970-01-01
      • 2011-10-17
      • 1970-01-01
      相关资源
      最近更新 更多