在我的Rails应用程序中,我有3个模型订单和出租车和旅客。以下是Order表的架构,其中 taxi_id 是出租车的外键, passenger_id 是乘客的外键
create_table "orders", force: :cascade do |t|
t.integer "passenger_id"
t.integer "taxi_id"
t.integer "price"
.
.
.
end
这是出租车架构:
create_table "taxis", force: :cascade do |t|
t.string "taxiNo"
t.string "address"
.
.
end
这是我的乘客架构
create_table "passengers", force: :cascade do |t|
t.string "name"
t.string "address"
t.string "destination"
end
乘客地址清除乘客的来源,出租车的地址定义了该出租车的当前地址。
我正在尝试运行此查询:
Taxi.joins(:orders => :passenger).select('taxis.id, orders.price, passengers.address, passengers.destination').where(:taxis =>{:id =>29 } ).all
事实上,我正在寻找乘客字段的价格,地址和目的地,但结果是[#<Taxi id: 29, address: "Narva mnt25, Tartu, Estonia">]
。
在这里你可以找到结果:
SELECT taxis.id, orders.price, passengers.address, passengers.destination FROM "taxis" INNER JOIN "orders" ON "orders"."taxi_id" = "taxis"."id" INNER JOIN "passengers" ON "passengers"."id" = "orders"."passenger_id" WHERE "taxis"."id" = 29
=> #<ActiveRecord::Relation [#<Taxi id: 29, address: "Narva mnt25, Tartu, Estonia">]>
它给了我Taxi_address,同时我要求订购Order.price,Passenger.address和Passenger.destination
重点:
我确定Taxi_id = 29存在
Taxi.find_by_id(29)
Taxi Load (0.2ms) SELECT "taxis".* FROM "taxis" WHERE "taxis"."id" = ? LIMIT 1 [["id", 29]]
=> #<Taxi id: 29, taxiNo: "T6", address: "Narva mnt25, Tartu, Estonia", status: "1", avalible_duration: 6, created_at: "2016-01-02 14:44:06", updated_at: "2016-01-02 14:44:06">
我相信我的订单表中有记录
Order.find_by_id(1)
Order Load (0.4ms) SELECT "orders".* FROM "orders" WHERE "orders"."id" = ? LIMIT 1 [["id", 1]]
=> #<Order id: 1, passenger_id: 40, taxi_id: 29, price: 925, created_at: "2016-01-04 04:40:52", updated_at: "2016-01-04 04:40:52">
答案 0 :(得分:0)
您的查询返回此原因的原因:
[#<Taxi id: nil>]
...是您未在查询中选择id
字段。您仍然可以获得记录,但它没有id
。这会解决它:
Taxi.joins(:orders).select('taxis.id, orders.price').where(:taxis =>{:id =>29 } )
但是,由于您需要orders
表中的字段,因此您应该查询订单模型,而不是Taxi模型:
Order.select(:id, :price).where(taxi_id: 29)
...虽然如果您只关心价值而不关心订单或出租车对象本身,请改用pluck
:
Order.where(taxi_id: 29).pluck(:price)
# => 925