开发者

Rails index of an association

开发者 https://www.devze.com 2022-12-16 01:14 出处:网络
I find myself requiring this.Assuming cart is a model which has a list of users开发者_运维技巧.

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消