2016-11-20 12 views
0

ParentModelにhas_many ChildModelがあるとします。Railsの検証 - 子モデルの作成中に親モデルを検証する

検証)を確認する方法はありParentModel子を作成中に(同じ名前の子レコードが存在する場合は?

+0

複合ユニークインデックスを探しているようですね。特定のフィールドと外部キーについて – axlj

+1

検証で名前の一意性だけをチェックする必要がある場合はOKですが、少し複雑にする必要があるので、メソッドを定義して検証用に使用することを考えていました。 – Ancinek

+0

多分この質問が役に立ちます:http:// stackoverflow。 com/questions/11849179/rails-validating-an-another-model-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

関連する問題