Ruby on Rails Saturday, October 29, 2011

On Oct 29, 1:31 am, Colin Law <clan...@googlemail.com> wrote:
> On 28 October 2011 22:46, Christopher J. Bottaro <cjbott...@gmail.com> wrote:
>
> > Hello,
> > What's the best/easiest way to write this delete statement using
> > ActiveRecord 3.1?
>
> > DELETE e1
> >   FROM events e1
> >   JOIN events e2
> >  WHERE e1.subject_type = e2.subject_type
> >    AND e1.subject_id   = e2.subject_id
> >    AND e1.origin_type  = e2.origin_type
> >    AND e1.origin_id    = e2.origin_id
> >    AND e1.id > e2.id
>
> Not answering the question I am afraid, but I think it is unwise to
> assume anything about the id sequence.  Presumably here you are
> assuming that id values are assigned in an increasing sequence, but I
> don't think this is necessarily guaranteed in the general case.  I
> think it might be better to use created_at, if that is what you really
> mean.  On the other hand if in reality you do not care which one you
> delete and have the id test only to make sure that you delete only one
> of them then please ignore my comment.
>
> Since you are interested in the best way to code it (rather than just
> hacking in the sql) then presumably it is something that happens
> routimnely rather than some tidying up operation that you have to do
> once.  Would it not be possible using validations or similar to ensure
> that the duplicate record situation does not happen in the first
> place?

All of this is true, and you should try these things before the
following.

You don't need a join. You're defining all your conditions on one
table just fine:

Event.where(:subject_type => e1.subject_type, ... ).where('id > ?',
e1.id).destroy_all

--
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.

No comments:

Post a Comment