Question

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?

Was it helpful?

Solution

Try this one:

u = User.new  
u.aliases.build

Hope this helps...

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top