Close
Glad You're Ready. Let's Get Started!

Let us know how we can contact you.

Thank you!

We'll respond shortly.

  • Blog Navigation
Standup 4/26/2010: Ruby hack night with Sarah Mei

Interesting Things

  • Given a list of IDs, how do you find which ones are not in the database?
ids = [1,2,3,4,5,0]
missing_ids = ids - Model.find_all_by_id(ids).collect(&:id)
  • Sarah Mei is hosting a Ruby Hack Night at pivotal labs tomorrow at 7PM (Tues April 27th. 731 Market St Floor 3, San Francisco).
  • There is an android users group tomorrow. We don’t know any more about it than that.
  • WT

    You don’t want to instantiate those objects. Wow.

    Use #select or use a method from ActiveRecord::ConnectionAdapters::DatabaseStatements.

    ids = [1,2,3,4444444]
    missing_ids = ids – Model.select(:id).where(id: ids).all.map(&:id)

  • Sam

    Yep, or pre r3:

    ids – Model.all(:conditions => {:id => ids}, :select => [:id]).collect(&:id)

    I thought that exists? might work for this, but you’d have to iterative over ids, generating loads more queries than you need. You can pass it conditions, but it will return a simple ‘true’ if ANY of the records have that ID.

  • David Stevenson

    Regardless of WT or Sam’s solution, you’re still instantiating objects. Thanks for pointing out that we should only be brining back the IDs, however, that can be a big performance win. If you really only want the IDs and not objects, you’d have to write straight SQL (which isn’t very rails friendly):

    ids – Model.connection.select_values(“SELECT `#{Model.primary_key}` FROM `#{Model.table_name}` WHERE `#{Model.primary_key}` IN (#{ids.join(“,”)})”).collect(&:to_i)

    The above statement doesn’t use adapter-specific column or table name quoting, which would have made it even more generic for non-mysql adapters.

  • Joseph Palermo

    Also, it wasn’t stated originally, but there was an object caching layer (via [cache money](http://github.com/nkallen/cache-money) I think) that direct SQL access would have bypassed.

  • You can pass it conditions, but it will return a simple ‘true’ if ANY of the records have that ID.

    remove

Share This