user985723
user985723

Reputation: 628

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?

Upvotes: 1

Views: 95

Answers (2)

nilay
nilay

Reputation: 365

Try this one:

u = User.new  
u.aliases.build

Hope this helps...

Upvotes: 1

Sachin R
Sachin R

Reputation: 11876

Use

ActiveRecord::Base.transaction do
  u = User.new(:name => "Bob")
  a = Alias.new(:name => "SirBob", :user_id => u)
end

and add validates_uniqueness_of :name on Alias model

This will solve your problem.

Upvotes: 0

Related Questions