How to choose where ID in Array Rails ActiveRecord without exception

When I have an array of identifiers like

ids = [2,3,5]

and I perform

Comment.find(ids)

everything is working fine. But when there is an id that does not exist, I get an exception. This happens in general when I get a list of identifiers that match some filter, and with what I do something like

current_user.comments.find(ids)

This time, I may have a valid comment identifier, which, however, does not belong to this user, so it is not found, and I get an exception.

I tried find(:all, ids), but it returns all records.

The only way to do it now is

current_user.comments.select { |c| ids.include?(c.id) }

But that seems like a super-inefficient solution to me.

Is there a better way to select an ID in an array without getting an exception from a nonexistent record?

+106
6

, , "find_all_by.." - .

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

, .

user.comments.find_all_by_id(potentially_nonexistent_ids)

.

: Rails 4

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

: Rails 4.x

:

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

, Relation, .where, .limit .., . .

Ruby :

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

(, ), :

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

.find .find_by_id 4. :

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

, .

user.comments.where(id: avoided_ids_array)

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

, , , , , .

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

ruby.

+1

named_scope,

, :

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

0

All Articles