我有这些模特:
class Car < ActiveRecord::Base
has_many :shared_cars
end
class SharedCar < ActiveRecord::Base
belongs_to :car
belongs_to :owner
acts_as_mappable :through => :car
end
class Owner < ActiveRecord::Base
has_many :shared_cars
end
car Service < ActiveRecord::Base
has_many :car_services
has_many :cars, through: :car_services
end
这是我的查询:
@cars = SharedCar.joins(:car)
.select('COUNT(cars.id) AS grouped_cars,
cars.registration,
cars.added_at')
.within(distance, origin: [lat,lng])
但是对于这个查询,我还需要添加services
。我试过了
@cars = SharedCar.joins(:car).includes(:services)
.select('COUNT(cars.id) AS grouped_cars,
cars.registration,
cars.added_at')
.within(distance, origin: [lat,lng])
错误:
Association named 'services' was not found; perhaps you misspelled it?
如何将模型服务正确附加到查询中?
答案 0 :(得分:0)
可能有帮助!
class Car < ActiveRecord::Base
has_many :shared_cars
has_many :car_services ##added
has_many :services, through: :car_services ##added
end
然后在您的查询中
@cars = SharedCar.joins(car: :services)
.select('COUNT(cars.id) AS grouped_cars,
cars.registration,
cars.added_at')
.within(distance, origin: [lat,lng])
答案 1 :(得分:0)
# car.rb
class Car < ActiveRecord::Base
has_many :shared_cars
has_many :car_services
end
# And query with include
@cars = SharedCar.joins(:car).includes(car: {car_services: :service}).select(
'COUNT(cars.id) AS grouped_cars,
cars.registration,
cars.added_at'
).within(distance, origin: [lat,lng]).references(:service)