How to select where ID in Array Rails ActiveRecord without exception

前端 未结 6 791
余生分开走
余生分开走 2020-12-07 16:13

When I have array of ids, like

ids = [2,3,5]

and I perform

Comment.find(ids)

everything works fine. But w

相关标签:
6条回答
  • 2020-12-07 16:44

    If you need more control (perhaps you need to state the table name) you can also do the following:

    Model.joins(:another_model_table_name)
      .where('another_model_table_name.id IN (?)', your_id_array)
    
    0 讨论(0)
  • 2020-12-07 16:47

    Update: This answer is more relevant for Rails 4.x

    Do this:

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

    The stronger side of this approach is that it returns a Relation object, to which you can join more .where clauses, .limit clauses, etc., which is very helpful. It also allows non-existent IDs without throwing exceptions.

    The newer Ruby syntax would be:

    current_user.comments.where(id: [123, "456", "Michael Jackson"])
    
    0 讨论(0)
  • 2020-12-07 16:53

    You can also use it in named_scope if You want to put there others conditions

    for example include some other model:

    named_scope 'get_by_ids', lambda { |ids| { :include => [:comments], :conditions => ["comments.id IN (?)", ids] } }

    0 讨论(0)
  • 2020-12-07 16:54

    Now .find and .find_by_id methods are deprecated in rails 4. So instead we can use below:

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

    It will work even if some of the ids don't exist. This works in the

    user.comments.where(id: avoided_ids_array)
    

    Also for excluding ID's

    Comment.where.not(id: [2, 3, 5])
    
    0 讨论(0)
  • 2020-12-07 17:00

    If it is just avoiding the exception you are worried about, the "find_all_by.." family of functions works without throwing exceptions.

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

    will work even if some of the ids don't exist. This works in the

    user.comments.find_all_by_id(potentially_nonexistent_ids)
    

    case as well.

    Update: Rails 4

    Comment.where(id: [2, 3, 5])
    
    0 讨论(0)
  • 2020-12-07 17:01

    To avoid exceptions killing your app you should catch those exceptions and treat them the way you wish, defining the behavior for you app on those situations where the id is not found.

    begin
      current_user.comments.find(ids)
    rescue
      #do something in case of exception found
    end
    

    Here's more info on exceptions in ruby.

    0 讨论(0)
提交回复
热议问题