加入 Rails 中的两个表,被称为 has_one: ".. ",class_name:"..."
Joining two tables in Rails ,which was mentioned as has_one: ".. ",class_name:"..."
class Transport::Vehicle < ApplicationRecord
has_one :driver, class_name: "Admin", foreign_key: "driver_id"
end
Transport::Vehicle.joins(:driver)
生成以下 SQL 查询
SELECT "transport_vehicles".* FROM "transport_vehicles" INNER JOIN "admins" ON "admins"."driver_id" = "transport_vehicles"."id" AND "admins"."deleted_at" IS NULL LIMIT
但应该是
SELECT "transport_vehicles".* FROM "transport_vehicles" INNER JOIN "admins" ON "admins"."id" = "transport_vehicles"."id" AND "admins"."deleted_at" IS NULL LIMIT
我怎样才能得到 admin.id 而不是 admins.driver_id ??
由于您的外键在 Transport::Vehicle class 上,您应该使用 belongs_to 而不是 has_one.
class Transport::Vehicle < ApplicationRecord
has_one :driver, class_name: "Admin", foreign_key: "driver_id"
end
Transport::Vehicle.joins(:driver)
生成以下 SQL 查询
SELECT "transport_vehicles".* FROM "transport_vehicles" INNER JOIN "admins" ON "admins"."driver_id" = "transport_vehicles"."id" AND "admins"."deleted_at" IS NULL LIMIT
但应该是
SELECT "transport_vehicles".* FROM "transport_vehicles" INNER JOIN "admins" ON "admins"."id" = "transport_vehicles"."id" AND "admins"."deleted_at" IS NULL LIMIT
我怎样才能得到 admin.id 而不是 admins.driver_id ??
由于您的外键在 Transport::Vehicle class 上,您应该使用 belongs_to 而不是 has_one.