Rails 4.1 包含未知列的范围失败
Rails 4.1 scope with includes failed with unknown column
将 rails 4.0 升级到 4.1 后,以下代码中断
Mysql2::Error: Unknown column 'user_groups.id' in 'where clause
scope :check_access, lambda {|user| includes(:user_groups).where('restrict_access is false or user_groups.id in (?)', user.get_user_group_ids) if user}
上面 rails 4.1 使用的正确语法是什么?
includes
不再保证您的来源 table 与包含关系之间的连接。 Rails 可以决定使用连接或通过两个单独的查询预加载关联信息。
除了 includes
之外,您还应该添加一个 references(:user_groups)
子句,这将为 ActiveRecord 提供足够的信息以了解您的意图。
scope :check_access, lambda { |user|
includes(:user_groups).references(:user_groups).where('restrict_access is false or user_groups.id in (?)', user.get_user_group_ids) if user
}
附带说明一下,如果用户记录存在,您的构造将 return 一个 ActiveRecord 关系,如果不存在,则 nil
。您最好使用 .none
方法来 return 空集合:
scope :check_access, lambda { |user|
if user
includes(:user_groups)
.references(:user_groups)
.where('restrict_access is false or user_groups.id in (?)', user.get_user_group_ids)
else
none
end
}
这样,check_access
将 始终 return 一个 ActiveRecord::Relation
集合对象,因此如果需要,您可以安全地将它与其他范围链接是。
将 rails 4.0 升级到 4.1 后,以下代码中断
Mysql2::Error: Unknown column 'user_groups.id' in 'where clause
scope :check_access, lambda {|user| includes(:user_groups).where('restrict_access is false or user_groups.id in (?)', user.get_user_group_ids) if user}
上面 rails 4.1 使用的正确语法是什么?
includes
不再保证您的来源 table 与包含关系之间的连接。 Rails 可以决定使用连接或通过两个单独的查询预加载关联信息。
除了 includes
之外,您还应该添加一个 references(:user_groups)
子句,这将为 ActiveRecord 提供足够的信息以了解您的意图。
scope :check_access, lambda { |user|
includes(:user_groups).references(:user_groups).where('restrict_access is false or user_groups.id in (?)', user.get_user_group_ids) if user
}
附带说明一下,如果用户记录存在,您的构造将 return 一个 ActiveRecord 关系,如果不存在,则 nil
。您最好使用 .none
方法来 return 空集合:
scope :check_access, lambda { |user|
if user
includes(:user_groups)
.references(:user_groups)
.where('restrict_access is false or user_groups.id in (?)', user.get_user_group_ids)
else
none
end
}
这样,check_access
将 始终 return 一个 ActiveRecord::Relation
集合对象,因此如果需要,您可以安全地将它与其他范围链接是。