How to select where ID in Array Rails ActiveRecord without exception

How to select where ID in Array Rails ActiveRecord without exception

Asked on January 11, 2019 in Ruby on Rails.
Add Comment


  • 3 Answer(s)

    The “find_all_by..” family of functions works without throwing exceptions.

    Comment.find_all_by_id([2, 3, 5])
    

    or

    user.comments.find_all_by_id(potentially_nonexistent_ids)
    

    Update: Rails 4

    Comment.where(id: [2, 3, 5])
    

    Answered on January 11, 2019.
    Add Comment

    Update:Rails 4.x

    current_user.comments.where(:id=>[123,"456","Michael Jackson"])
    

       A Relation object join more .where clauses, .limit clauses, etc.,It also allows non-existent IDs without throwing exceptions.

    current_user.comments.where(id: [123, "456", "Michael Jackson"])
    

    Answered on January 11, 2019.
    Add Comment

    Alternative solution for Array Rails ActiveRecord : 

    Model.joins(:another_model_table_name)
      .where('another_model_table_name.id IN (?)', your_id_array)
    

    Answered on January 11, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.