【问题标题】:The second argument of Ecto.Query.from/2Ecto.Query.from/2 的第二个参数
【发布时间】:2017-08-26 00:25:30
【问题描述】:

我在尝试使用 Ecto.Query.from/2 构建查询时遇到了一个奇怪的错误。 请看下面的代码:

iex(24)> import Ecto.Query, only: [from: 2]
nil
iex(25)> from User, limit: 1 # valid
#Ecto.Query<from u in Jcb.User, limit: 1>

iex(26)> opts = [limit: 1]
[limit: 1]
iex(27)> Keyword.keyword? opts
true

iex(28)> from user, opts
** (ArgumentError) second argument to `from` must be a keyword list
    (ecto) expanding macro: Ecto.Query.from/2
           iex:28: (file)

我找到了源代码here,但我不确定它是否是错误。请帮忙。
谢谢!

【问题讨论】:

    标签: elixir phoenix-framework ecto


    【解决方案1】:

    和灵药有关macros

    这是因为函数调用的参数是在调用函数之前计算的。但是,宏不评估它们的参数。相反,它们将参数作为带引号的表达式接收,然后将其转换为其他带引号的表达式。

    defmodule Mod do
      defmacro test_macro(kw \\ []) do
        IO.puts inspect(kw)
        IO.puts Keyword.keyword?(kw)
        quote do
          Keyword.keyword?(unquote(kw))
        end
      end
    end
    
    > import Mod
    
    > test_macro []
    []
    true
    true
    
    
    > kw = []
    > test_macro kw
    {:kw, [line: 63], nil}
    false
    true
    

    【讨论】:

      【解决方案2】:

      在这种情况下,问题的解决方案可能是:

      limit = 1
      from User, limit: ^limit
      

      在不需要限制的情况下,limit 可以设置为nil

      limit = nil
      from User, limit: ^limit  # unlimited results (at least with postgresql)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-22
        • 2018-06-26
        • 1970-01-01
        • 1970-01-01
        • 2013-10-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多