为什么Rails警告我一个不存在的SQL片段?

时间:2016-06-15 03:36:40

标签: ruby-on-rails ruby rails-activerecord

我正在尝试从Rails 3.2到Rails 4获取应用程序。

我的代码中的一个特定点是吐出这个警告:

DEPRECATION WARNING: It looks like you are eager loading table(s)
(one of: users, one.example) that are referenced in a string SQL
snippet. For example: 

    Post.includes(:comments).where("comments.title = 'foo'")

Currently, Active Record recognizes the table in the string, and
knows to JOIN the comments table to the query, rather than loading
comments in a separate query. However, doing this without writing
a full-blown SQL parser is inherently flawed. Since we don't want
to write an SQL parser, we are removing this functionality. From
now on, you must explicitly tell Active Record when you are
referencing a table from a string:

    Post.includes(:comments).where("comments.title = 'foo'")
        .references(:comments)

If you don't rely on implicit join references you can disable the
feature entirely by setting
`config.active_record.disable_implicit_join_references = true`.
(called from authenticate_common at
/path/to/project/app/models/user.rb:72)

但有问题的行甚至不包含SQL:

def self.authenticate_common(login, password)
  return nil if login.blank? || password.blank?
  # this line outputs the warning:
  user = User.includes(INCLUDES_FOR_AUTH).where(:login => login).first
  # and so does this line
  user ||= User.includes(INCLUDES_FOR_AUTH).where(:email => login).first
  return nil unless user && user.authenticated?(password)
  user
end

此处的条件不仅不使用SQL,而且甚至不引用任何相关模型,因此无法执行建议的修复。此外,User类中没有可以添加任何默认条件的范围。

INCLUDES_FOR_AUTH的值为:

INCLUDES_FOR_AUTH = [{ :roles => [ :permissions ]}]

RolePermission类也缺少任何SQL代码段,因此不能是它们。

我唯一剩下的想法是,Rails可能正在生成SQL片段,然后在自己的检查中绊倒自己...是发生了什么? :/

到目前为止的调查:

  • 将包含设置为[]后,警告仍会显示。
  • 从所有模型类的范围中删除所有order次调用后,仍会显示警告。
  • 如果我在整个代码中将调用分散到references(:user),它会清除警告。我猜这只是掩盖了问题,因为手头的问题是我不确定为什么我必须首先打电话给references,如果我必须打电话给我,我我希望在导致需要它的代码旁边这样做,而不是到处都是。
  • 它最终运行的查询对我来说没有多大意义,因为它们似乎没有返回实际记录:

    SELECT 1 AS AS FROM“users”WHERE“users”。“login”='someone@somewhere.com'LIMIT 1
    SELECT 1 AS one FROM“users”WHERE“users”。“email”='someone@somewhere.com'LIMIT 1

    从查询来看,似乎where子句是我提供的数据中唯一使用的子句,但是那里的SQL肯定是由Rails本身创建的。

0 个答案:

没有答案