2016-11-20 166 views
0

假設我有ParentModel has_many ChildModelRails驗證 - 在創建子模型時驗證父模型

有沒有一種方法來檢查(驗證ParentModel而創建子(例如像檢查是否具有相同名稱的子記錄存在?

+0

所以這聽起來像你可能正在尋找一個複合獨特的索引?在特定的字段和外鍵上? – axlj

+1

如果驗證應該只檢查名稱唯一性,但是它必須稍微複雜一些,所以我想定義一個方法並將其用於驗證 – Ancinek

+0

也許這個問題會有所幫助:http:// stackoverflow。 com/questions/11849179/rails-validation-an-attribute-based-on-another-model – axlj

回答

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, 
+0

您的解決方案非常簡單。我最終創建了一個自定義方法,並使用'self'訪問創建的(尚未保存的)子項的父項 – Ancinek