轨道,包括关联



我有国家,汽车,租赁类型和汽车类型模型。

Country Model
has_many :cars
Car Model
belongs_to :country
belongs_to :car_group
RentalType Model
has_many :car_rentals
has_many :cars, :through => :car_rentals
has_many :car_group_types
has_many :car_groups, :through => :car_group_types

CarGroup Model
has_many :cars
has_many :car_group_types
has_many :rental_types, :through => :car_group_types

所以我想得到属于这个国家的汽车,它的租赁类型名称是"清醒",car_group名称是"丰田"。

到目前为止,我已经尝试过;

b = @country.cars.includes(:rental_types).where(:rental_types => { name: @rental_type.name } ).all

这工作正常,但是当我尝试添加汽车组时,它会出现错误;

b = @country.cars.includes(:rental_types).where(:rental_types => { name: @rental_type.name } ).where(:car_group => { name: @car_group.name } ).all

错误:

SQLite3::SQLException: no such column: car_group.name: SELECT DISTINCT COUNT(DISTINCT "cars"."id") FROM "cars" LEFT OUTER JOIN "car_rentals" ON "car_rentals"."car_id" = "cars"."id" LEFT OUTER JOIN "rental_types" ON "rental_types"."id" = "car_rentals"."rental_type_id" LEFT OUTER JOIN "car_groups" ON "car_groups"."id" = "cars"."car_group_id" WHERE "cars"."car_country_id" = ? AND "rental_types"."name" = ? AND "car_group"."name" = ?
  • :car_group添加到您的:includes

    includes(:rental_types, :car_group)

  • :car_group应该是:where中的plural名词:

    where(:car_groups => { name: @car_group.name } )

最新更新