【问题标题】:Rails - search through has_many associationRails - 通过 has_many 关联搜索
【发布时间】:2016-07-06 09:37:58
【问题描述】:
我有这些模型:
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
但由于模型关联使用错误,此查询不起作用。
我如何知道当前的汽车是否有一些安全气囊?
提前谢谢你。
【问题讨论】:
标签:
ruby-on-rails
ruby
associations
has-many
【解决方案1】:
假设你的迁移没问题
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
【解决方案2】:
好吧,从关系的角度来看,我假设car_services 是cars 和car_service_definitions 的富连接表
你可以做的是在car和car_service_definition上建立has_many :through关系
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