Ruby on Rails Sunday, October 30, 2011

On Oct 29, 3:26 pm, Kurt Werle <k...@circlew.org> wrote:
> On Oct 29, 1:31 am, Colin Law <clan...@googlemail.com> wrote:
> 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

This doesn't do the same thing as the original query. This deletes all
the events which have the same subject_type etc as a specific event
e1, but created after e1, i.e. remove what you might consider
duplicates of the specific event e1. The original query on the other
hand deletes all duplicates, not only those that are duplicates of a
specific even.

Personally I would just use the raw sql in a call to delete_all. A
complicated use of arel isn't necessarily "better" or easier to use
than sql (portability concerns aside, but then the whole idea that you
can move any significantly sized app just by changing a line in
database.yml is a bit of a myth anyway).

you could do something like

class Event < ..
def self.duplicate_events
event_alias = Event.arel_table.alias
scoped.joins(event_alias).where(:subject_id =>
event_alias[:subject_id], ...).where(Event.arel_table[:id].gt(event_alias[:id]))
end
end

which gives you an Event.duplicate_events scope

unfortunately (at least with the version of ActiveRecord/Arel in rails
3.0.x you can't do Event.duplicate_events.delete_all, because the bit
of Arel that deals with deletes always does "delete from blah" and
doesn't allow you to say "delete t1 from t1 join t2, ..."


Fred

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