Reputation: 628
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
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