【问题标题】:Rails 5 Model Association has_many :through, validate child can only belong to one parentRails 5 模型关联 has_many :通过,验证孩子只能属于一个父母
【发布时间】:2017-11-09 20:25:15
【问题描述】:

有问题的 3 个模型。停电,孩子,关系。

一次中断可以产生许多子节点。 一个孩子属于停电。 关系是中间人表。

一个子节点一次只能属于一次中断(即,如果子节点 123 属于中断 A,则您不能将子节点 123 与不同的中断关联)

每次中断中的子节点必须是唯一的。 (我已经在Relationship 模型中使用validates_uniqueness_of 解决了这个问题)。

class Outage < ApplicationRecord
    has_many :relationships
    has_many :children, :through => :relationships
end

class Child < ApplicationRecord
    has_many :relationships
    has_many :outages, :through => :relationships 
end

class Relationship < ApplicationRecord
    belongs_to :outage
    belongs_to :child
    validates_uniqueness_of :outage_id, :scope => :child_id
end

我尝试过像这样设置自定义验证器(在 child.rb 中):

def has_one_outage
    if outages.length > 1
        errors.add(:base, "a child can only belong to one outage at a time")
    end
end  

但该验证似乎没有影响。

对我在这里做错了什么有任何见解吗?

【问题讨论】:

  • 那为什么不能使用has_one 而不是has_many
  • 为什么不在您的Child 模型上使用has_one :relationshiphas_one :outage, :through =&gt; :relationshipRails Guide 描述了这种关联。
  • @TomAranda 对,我就是这么想的。试过了,但这仍然允许孩子与不同的中断相关联。
  • 您可能想要添加一个唯一索引,如链接指南中所述。
  • @TomAranda 您的意思是为child_id 创建一个唯一索引,对吗? t.index ["child_id"], name: "index_relationships_on_child_id", unique: true

标签: ruby-on-rails activerecord model-associations


【解决方案1】:

能够通过以下方式解决它:

class Outage < ApplicationRecord
    has_many :relationships
    has_many :children, through: :relationships
end


class Child < ApplicationRecord
    has_many :relationships
    has_many :outages, through: :relationships
end


  class Relationship < ApplicationRecord
    belongs_to :child
    belongs_to :outage
    validate :ensure_one_relationship

    def ensure_one_relationship
      if Relationship.where(child_id: self.child_id).present?
          errors.add(:base, "A trouble ticket can only be associated with one outage ticket.")
      end
    end
  end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-24
    • 1970-01-01
    相关资源
    最近更新 更多