[Rails] rescuing ActiveRecord::RecordNotUnique: clever or ugly?
I have an ActiveRecord that has several foreign keys, where the foreign
keys act as a single compound key that needs to be unique:
class CreateRelations < ActiveRecord::Migration
def change
create_table :relations do |t|
t.references :src, :null => false
t.references :dst, :null => false
end
add_index :relations, [:src_id, :dst_id], :unique => true
end
end
One obvious way to enforce uniqueness would be using first_or_create:
def self.create_relation(src, dst)
where(:src_id => src.id, :dst_id => dst.id).first_or_create!
end
Which works, but that always does a SELECT before creating the record.
Since I don't expect users to attempt to create duplicates very often,
I've written a the method to catch RecordNotUnique errors, like this:
def self.create_relation(src, dst)
create!(:src => src, :dst => dst)
rescue ActiveRecord::RecordNotUnique
where(:src_id => src.id, :dst_id => dst.id)
end
So mine is a question of style: is this considered an abuse of rescue?
Or is how seasoned Rails programmer would do this?
- ff
--
Posted via http://www.ruby-forum.com/.
--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home