简体   繁体   English

Rails-如何仅从ActiveRecord对象获取特定记录?

[英]Rails - how to fetch from ActiveRecord object only specific records?

I get this from an ActiveRecord call: 我是从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>]>

Once I get this, I need to filter only records where car_type = "0" . 一旦获得此信息,我只需要过滤car_type = "0"记录。 How to do that without doing another database call ( WHERE car_type = "0" )? 如何在不执行另一个数据库调用的情况下做到这一点( WHERE car_type = "0" )?

Thank you in advance. 先感谢您。

EDIT: 编辑:

this: 这个:

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

does not work. 不起作用。

just convert your result to an array then filter it like this 只是将您的结果转换为数组,然后像这样过滤它

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

You can use scope in CarService model: 您可以在CarService模型中使用范围:

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

and you can use it like this: 您可以像这样使用它:

car.car_services.type_ones

If you use enum, it will be better. 如果使用枚举,那会更好。 Because the enum creates to scopes automatically instead of you. 因为枚举会自动代替您创建作用域。 And of course it has more features. 当然,它具有更多功能。 More about the enum . 有关枚举的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM