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?

有帮助吗?

解决方案

Try this one:

u = User.new  
u.aliases.build

Hope this helps...

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top