Elixir/Phoenix restrict params like Rails strong params

后端 未结 2 1712
忘了有多久
忘了有多久 2021-01-20 09:51

I am making an API only Phoenix app. I come from a Ruby on Rails background, so bear with me.

Say I have a User model with email, password,

相关标签:
2条回答
  • 2021-01-20 10:19

    Actually the code behaves as expected and does not save the role field. (I was reading the request in the console instead of actually checking the database.)

    0 讨论(0)
  • 2021-01-20 10:25

    I know this is late here but here is this approach:

    defmodule MyApp.Utils do
      def strong_params(params, allowed_fields) when is_map(params) do
        allowed_strings = Enum.map(allowed_fields, &Atom.to_string(&1))
    
        Enum.reduce(params, [], fn {k, v}, acc ->
          key = check_key(k, allowed_strings)
          acc ++ [{key, v}]
        end)
        |> Enum.reject(fn {k, _v} -> k == nil end)
        |> Map.new()
      end
    
      defp check_key(k, allowed_strings) when is_atom(k) do
        str_key = Atom.to_string(k)
    
        if str_key in allowed_strings do
          k
        end
      end
      defp check_key(k, allowed_strings) when is_binary(k) do
        if k in allowed_strings do
          String.to_existing_atom(k)
        end
      end
      defp check_key(_, _), do: nil
    end
    

    Reference: https://medium.com/@alves.lcs/phoenix-strong-params-9db4bd9f56d8

    0 讨论(0)
提交回复
热议问题