Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails index of an association

I find myself requiring this. Assuming cart is a model which 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's an easier way to get the index of an association like this?

like image 492
cmaughan Avatar asked Jan 13 '10 08:01

cmaughan


1 Answers

The index method on Array does the same as your index_of_item method e.g.

cart.users.index(current_user)

Returns the index of the first object in the array that is == to obj. Returns nil if no match is found.

like image 163
mikej Avatar answered Oct 06 '22 19:10

mikej