【问题标题】:Rails 3: Scope returns an arrayRails 3:范围返回一个数组
【发布时间】:2011-12-15 15:14:13
【问题描述】:

我正在使用范围来获取特定用户的项目:

在物品模型中

belongs_to :user    
scope :for_user, lambda { |user| where(:user_id => user) }

用户模型

has_many :items

问题

当调用Item.includes(:user).for_user(3) 时,会返回一个数组而不是一个 ActiveRecord 关系。 我希望它的行为类似于 Item.includes(:user).find_by_user_id(3),它返回一个 ActiveRecord 关系。

感谢您的帮助。

【问题讨论】:

    标签: ruby-on-rails activerecord scope


    【解决方案1】:

    如果您进行更多调查,您会发现它确实返回了一个关系对象。

    但它会在必要时将其转换为数组。

    也就是说,如果您在控制台中说> Item.includes(:user).for_user(3),它将尝试检查它,然后进行转换。

    但无论如何以下方法都会起作用

    scope = Item.includes(:user).for_user(3)
    
    # does a db count
    scope.count
    
    # does a db select limit 1
    scope.first
    
    # does a full db select
    scope.all
    

    【讨论】:

    • 啊..当您说“ActiveRecord 关系对象”时,您的意思是“ActiveRecord”还是“ActiveRecord 关系”?这是两个不同的东西。
    【解决方案2】:

    使用where(:user_id => user) 而不是像 find_by_user_id 这样的动态方法将始终返回一个数组。如果您只对从您的范围返回的第一条记录感兴趣,您可以将您的范围更改为类似

    scope :for_user, lambda { |user| where(:user_id => user).first }
    

    【讨论】:

    • 这对我不起作用。它执行以下操作:SELECT cities.* FROM cities WHERE cities.name = 'Berlin' LIMIT 1 SELECT cities.* FROM cities。最终得到一个数组。
    猜你喜欢
    • 2017-03-04
    • 2020-04-14
    • 2016-04-02
    • 1970-01-01
    • 2013-08-22
    • 1970-01-01
    • 1970-01-01
    • 2021-08-31
    • 1970-01-01
    相关资源
    最近更新 更多