Rails验证 - 在创建子模型时验证父模型

时间:2016-11-20 16:34:10

标签: ruby-on-rails

假设我有ParentModel has_many ChildModel

创建子项时是否有办法检查(验证ParentModel(例如检查是否存在具有相同名称的子记录?

1 个答案:

答案 0 :(得分:2)

这非常简单,如果错误,请纠正我。

def Parent 
    has_many :children 
end 
def Child
    belongs_to :parent
    #Here you could run some validations, for example:
    validates :name,presence: true, length: { minimum: 1 },uniqueness: { scope: :parent_id }
    #by running uniqueness with scope, you can repeat names, but not associated with the same parent. 
end 

然后可以,例如:

p = Parent.first #suppose we already have the parent
p.child.new  #create a child, with attributes if needed 
p.valid? #p won't be valid unless his new child is

替代:

p = Parent.first #suppose we already have the parent
c = Child.new  #create a child, with attributes if needed 
p.children << c #append the child to the collection, if C is invalid, then it won't be saved into the database
p.valid?   #validate,