Rails Association Index

I demand it. An estimated basket is a model that has a list of users.

def index_of_item
 cart.users.each_with_index do |u, i|
  if u == current_user
   return i
 end
end

What is an easy way to get the index of such an association?

+5
source share
1 answer

Method index on Arraydoing the same thing as your method index_of_item, for example.

cart.users.index(current_user)

Returns the index of the first object in the array, which is == for obj. Returns nilif no match is found.

+10
source

All Articles