Rails - 搜索has_many关联

时间:2016-07-06 09:37:58

标签: ruby-on-rails ruby associations has-many

我有这些模特:

class Car < ActiveRecord::Base
  has_many :car_services
end
class CarService < ActiveRecord::Base
  belongs_to :car
  belongs_to :car_service_definition
end
class CarServiceDefinition < ActiveRecord::Base
  has_many :car_services
end

我试图找出当前选择的汽车是否有某项服务 - 尝试这样做:

airbag = car.car_services.car_service_definitions.where('service_type = "Airbag"').first

但由于使用模型关联错误,此查询无法正常工作。

如果当前的汽车有一些安全气囊怎么办?

提前谢谢。

2 个答案:

答案 0 :(得分:2)

假设你的迁移很好

class Car < ActiveRecord::Base
  has_many :car_services
end
class CarService < ActiveRecord::Base
  belongs_to :car
  belongs_to :car_service_list
  has_and_belongs_to_many :car_service_definitions
end
class CarServiceDefinition < ActiveRecord::Base
end

airbag = car.car_services.car_service_definitions.where(service_type: 'AirBag').first

答案 1 :(得分:0)

嗯,从关系的角度来看,我认为car_servicescarscar_service_definitions

的丰富联接表

您可以做的是在has_many :throughcar上设置car_service_definition关系

class Car < ActiveRecord::Base
  has_many :car_services
  has_many :car_service_definitions, through: :car_services
end

class CarService < ActiveRecord::Base
  belongs_to :car
  belongs_to :car_service_definition
end

class CarServiceDefinition < ActiveRecord::Base
  has_many :car_services
  has_many :cars, through: :car_services
end

然后如果你想找到安全气囊,那就像这样

airbag = car.car_service_definitions.where("car_service_definitions.service_type" => 'AirBag').first

但是如果你想检查car是否有air_bag,可以写一个像这样的方法

class Car < ActiveRecord::Base
  def has_air_bag?
    car_service_definitions.where("car_service_definitions.service_type" => 'AirBag').count > 0
  end
end
相关问题