Elixir 中的动态代码

Dynamic code in Elixir

我正在尝试在我的 Repo 中对此 table 进行查询:

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

在我的代码中,我将列的名称作为字符串获取(例如 variable = "create_author")。如何将 variable 插入到我的查询中?

当我对 create_author 进行硬编码时,它确实有效:

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

我希望能够输入 variable = "read_author"variable = :read_author

您可以为此使用 field 表达式:

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

如果您有字符串,可以使用 String.to_existing_atom/1String.to_atom/1.

将其转换为原子