[英]Rails validation - validate parent model while creating child model
假設我有ParentModel
是HAS_MANY ChildModel
。
有沒有一種在創建ParentModel
時檢查( 驗證 ) ParentModel
的方法(例如,檢查是否存在同名子代記錄?
這很簡單,如果有誤,請糾正我。
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,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.