【问题标题】:Rails - how to fetch from ActiveRecord object only specific records?Rails - 如何从 ActiveRecord 对象中仅获取特定记录?
【发布时间】:2016-10-29 11:56:55
【问题描述】:

我从 ActiveRecord 调用中得到这个:

#<ActiveRecord::Associations::CollectionProxy [
  #<CarService id: nil, car_id: nil, car_service: 1, 
               created_at: nil, updated_at: nil, car_type: 0>, 
  #<CarService id: nil, car_id: nil, car_service: 11,
               created_at: nil, updated_at: nil, car_type: 1>]>

一旦我得到这个,我只需要过滤car_type = "0" 的记录。如何在不进行另一个数据库调用 (WHERE car_type = "0") 的情况下做到这一点?

提前谢谢你。

编辑:

这个:

car.car_services.select{|key, hash| hash['car_type'] == "1" }

不工作。

【问题讨论】:

  • car.car_services.select{ |car_service| car_service.car_type.to_s == "1" }。顺便说一句,这是错误的方法。另一个针对 DB 的过滤查询会更快、更可靠。
  • 你试过了吗:car.car_services.select{|car_service| car_service.car_type == 1 }
  • 为什么不where?如果结果很大,select 会花很长时间。如果查询全部完成,则不会再拨打电话
  • 你能展示你原来的 ActiveRecord 调用吗? ActiveRecord 和 ActiveRelation 允许链接调用来优化你的 sql。这不会导致多个 sql 执行。如果我们知道您最初调用的内容,我们可能会附加一个限制您想要的方式的位置。

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


【解决方案1】:

只需将结果转换为数组,然后像这样过滤它

result = car.car_services.to_a.select do |e|
     e.car_type == "0"
end

【讨论】:

【解决方案2】:

您可以在 CarService 模型中使用范围:

scope :type_ones, -> { where(car_type: 1) }

你可以这样使用它:

car.car_services.type_ones

如果你使用枚举,它会更好。因为枚举会自动创建范围而不是您。当然,它还有更多功能。更多关于enum

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    • 1970-01-01
    • 2014-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多