I''m working on a script to propagate the database for my Rails app, and
I''m
running into trouble with ''validates_uniqueness_of'' not
behaving the way I
want/expect.
I have a simple table of organizations ...
class Organization < ActiveRecord::Base
validates_presence_of :name
validates_uniqueness_of :name
...
end
I need to ensure that an organization exists in the DB, and be able to
retrieve its id, before I start assigning people to it. So I tried:
org = Organization.new( ''name'' => "Some
Organization", ... )
org.save
orgid = org.id
This does work, when "Some Organization" *doesn''t* exist, but
when it does,
orgid is nil. I expected AR to create the org if it doesn''t exist, but
also
to SELECT the org if it already exists. Since it appears not to work this
way, I need to resort to:
org = Organization.find_by_name( "Some Organization" )
if org.nil?
org = Organization.new( ''name'' => "Some
Organization", ... )
org.save
end
orgid = org.id
But I can''t shake the feeling that there has *got* to be a better way.
Can
anyone throw some clue my way?
Thanks ..
-- Steve