Search code examples
elixirecto

Dynamic code in Elixir


I'm trying to make a query to this table in my Repo:

 user_id | create_author | delete_author | update_author | read_author
----------------------------------------------------------------------
   1     |   true        |    false      |    false      |   true

In my code, I get the column's name as a string (e.g. variable = "create_author"). How can I insert variable into my query?

When I have hardcoded create_author it does work:

def auth() do
    App.Permission
    |> where(user_id: ^Map.get(current_user, :id))
    |> where(read_author: true)
    |> Repo.one()
    |> case do
      nil -> false
      _user -> true
    end
end

I want to be able to enter a variable = "read_author" or variable = :read_author


Solution

  • You can use a field expression for this:

    def auth() do
      variable = :read_author
      App.Permission
      |> where(user_id: ^Map.get(current_user, :id))
      |> where([p], field(p, ^variable) == true) # <- this
      |> Repo.one()
      |> case do
        nil -> false
        _user -> true
      end
    end
    

    If you have a string, you can convert it to an atom using String.to_existing_atom/1 or String.to_atom/1.