【问题标题】:Combining active record relations结合活动记录关系
【发布时间】:2016-07-01 13:29:46
【问题描述】:

给定这两个活动记录关系对象

cars = Vehicle.where(type: 'car') # ActiveRecord::Relation
motorbikes = Vehicle.where(type: 'motorbike') # ActiveRecord::Relation

我可以通过什么方式将这两个对象组合成一个包含汽车和摩托车的对象,我可以在上面使用主动记录方法?有可能吗?

编辑: 这与过去类似性质的问题有所不同,因为我是在 Rails 5 的背景下专门询问的。

【问题讨论】:

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


    【解决方案1】:

    在 Rails 中,你可以这样做:

    cars_and_bikes = Vehicle.where(type: ['car', 'motorbike'])
    

    或者使用新的 Rails 5 AR#or 你可以这样做:

    cars_and_bikes = Vehicle.where(type: 'car').or(Vehicle.where(type: 'motorbike'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-12
      • 1970-01-01
      相关资源
      最近更新 更多