Search code examples
elixirecto

how to simplify the nil check for params's condition?


The URL is as follows:

http://localhost:4000/pictures?product_id=4970

I want to list all pictures related to a specified product_id. The relationship between picture and product are many-to-many.

The controller's list picture code is as follows:

  def list_pictures(attr = params) do
    product_id = Map.get(attr, "product_id")
    a =
      case product_id do
        nil ->
          Picture

        _ ->
          picture_list = from(p in Mirror.Imports.ProductPicture,
            where: p.product_id == ^product_id,
            select: p.picture_id
          )
          from(p in Mirror.Imports.Picture,
          where: p.id in subquery(picture_list)
          )
      end

    a
    |> preload(:product)
    |> Repo.all()
  end

I have a product_id check in the code, how to simplify it? Can you help me?


Solution

  • How about?

      def list_pictures(%{"product_id" => product_id}) when not is_nil(product_id) do
        picture_list = from(p in Mirror.Imports.ProductPicture,
          where: p.product_id == ^product_id,
          select: p.picture_id
        )
        from(p in Mirror.Imports.Picture,
          where: p.id in subquery(picture_list)
        )
        |> preload(:product)
        |> Repo.all()
      end
    
      def list_pictures(_attrs) do
        Picture
        |> preload(:product)
        |> Repo.all()
      end
    

    P.S. I would consider a join instead of the subquery