これ
u = User.first
u.clients.find_or_create_by_email('example@example.com')
has_many 関係が設定されている場合に機能します。ただし、Client オブジェクトに検証が設定されている場合は検証エラーは発生せず、検証が失敗した場合は黙って失敗します。
実行すると、コンソールで出力を確認できます
u.clients.find_or_create_by_email('example@example.com') # => #<Client id: nil, email: 'example@example.com', name: nil, user_id: 1, another_attribute: nil, active: true, created_at: nil, updated_at: nil>
検証が失敗し、クライアントが作成されていないため、user_id は設定されますが、クライアントの ID は設定されません。
したがって、クライアント オブジェクトの必要な属性をすべて渡し、クライアント オブジェクトの検証が成功した場合にのみ、クライアントが作成されます。
したがって、クライアントモデルに電子メールとは別に名前の検証があるとしましょう。
u.clients.find_or_create_by_email_and_name('example@example.com', 'my_name') #=> #<Client id: 1, email: 'example@example.com', name: 'my_name', user_id: 1, another_attribute: nil, active: true, created_at: "2009-12-14 11:08:23", updated_at: "2009-12-14 11:08:23">