From: Robert Klemme Date: 2010-06-17T15:20:10+09:00 Subject: Re: Compare two objects On 16.06.2010 13:11, Greg Ma wrote: > I have an array of events comming from a database and I have a new > object (so without an id). > I would like to check if my new object already exists in the database. > I tried exists? and include? but obviously id doesn't work because my > new object has no id. > Is there a simple way to compare my object or I will have to compare > each attribute? Basically it boils down to that - there is no other way. How you do that is less clear, there are several options. You can do the check in memory if you have to load existing objects anyway. But you should also have proper constraints in the database which ensure you do not have duplicate instances. These should be used to avoid inserting a duplicate. You then only need to catch the error. Which brings us to the topic of primary keys: there is a lot debate about whether a numeric id is better or a composite PK which comprises key properties of your entity (class). There are arguments in favor of one and the other but even if you make the PK a surrogate key you should have a constraint which prevents duplicates according to your real PK. In a RDBMS uniqueness constraints are usually checked efficiently via an index which you can use to quickly check for the existing of a particular instance in the db. But see Brian's remark about race conditions. IMHO directly inserting and catching the error is the superior approach. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/