Search code examples
ruby-on-railsrelationships

Rails: Confirming two objects were saved at the same time?


When a user is created on my site I want a User.new instance to execute but I also need to make a Alias.new object too. Users have many Aliases. However, I also need to validate that there are no other Aliases with that name before saving.

From the console my code might look like this:

u = User.new(:name => "Bob")
a = Alias.new(:name => "SirBob", :user_id => u)

But that's doesn't work since u doesn't have a id until I save. So how do I validate both items for uniqueness of name before saving them?


Solution

  • Try this one:

    u = User.new  
    u.aliases.build
    

    Hope this helps...