过滤不同资源列表的id

Filter the ids of a list of different resources

设置

mix phx.gen.html Products Fruit fruits name
mix phx.gen.html Products Vegetable vegetables name

我有一份 products 水果和蔬菜清单:

products = []
products = products ++ Products.get_fruits!(1)
products = products ++ Products.get_vegetables!(1)
products = products ++ Products.get_fruits!(2)

问题

如何获取列表 products 中所有 fruits 和所有 vegetablesid

我想到了这样的事情:

vegetable_ids = []
fruit_ids = []

for product <- products do
  case product do
    %Abc.Products.Vegetable{__meta__: _, id: id, inserted_at: _, name: _, updated_at: _} -> vegetable_ids = vegetable_ids ++ [id]
    %Abc.Products.Fruit{__meta__: _, id: id, inserted_at: _, name: _, updated_at: _} -> fruit_ids = fruit_ids ++ [id]
  end
end

有没有更好更简单的过滤所有 ID 的方法?

我会改用 2 for,利用 for 忽略与模式不匹配的元素而不是引发错误这一事实。也无需对要忽略的字段进行模式匹配。

vegetable_ids = for %Abc.Products.Vegetable{id: id} <- products, do: id
fruit_ids = for %Abc.Products.Fruit{id: id} <- products, do: id