【发布时间】:2019-01-20 02:18:22
【问题描述】:
在我的应用程序中,我有以下模型
费用.rb
class Fee < ActiveRecord::Base
acts_as_paranoid
belongs_to :instructor_student
belongs_to :instructor
has_many :fee_payment_notifications, dependent: :destroy
end
fee_payment_notifications.rb
class FeePaymentNotification < ActiveRecord::Base
belongs_to :fee
end
instructor.rb
class Instructor < ActiveRecord::Base
has_many :fees
has_many :fee_payment_notifications, through: :fees
end
我想通过费用支付通知来做内部加入费用 当我直接将费用加入与费用支付通知一起使用时,它会给我以下错误
@instructor.fee_payment_notifications.joins(:fee)
PG::UndefinedTable: ERROR: invalid reference to FROM-clause entry for table "fees"
LINE 1: ..."."id" = "fee_payment_notifications"."fee_id" AND "fees"."de...
^
HINT: Perhaps you meant to reference the table alias "fees_fee_payment_notifications".
: SELECT "fee_payment_notifications".* FROM "fee_payment_notifications" INNER JOIN "fees" "fees_fee_payment_notifications" ON "fees_fee_payment_notifications"."id" = "fee_payment_notifications"."fee_id" AND "fees"."deleted_at" IS NULL INNER JOIN "fees" ON "fee_payment_notifications"."fee_id" = "fees"."id" WHERE "fees"."deleted_at" IS NULL AND "fees"."instructor_id" = $1
可能是因为 deleted_at 字段,这就是为什么我想使用以下查询进行手动连接
@instructor.fee_payment_notifications.select("fee_payment_notifications.* from fee_payment_notifications AS fp INNER JOIN fees as f ON fp.fee_id = f.id")
它给了我以下错误
PG::SyntaxError: ERROR: "FROM" 处或附近的语法错误 第 1 行: ...ns AS fp INNER JOIN 费用为 f ON fp.fee_id = f.id FROM "fee_... ^ : SELECT fee_payment_notifications.* from fee_payment_notifications AS fp INNER JOIN fee as f ON fp.fee_id = f.id FROM "fee_payment_notifications" INNER JOIN "fees" ON "fee_payment_notifications"."fee_id" = "fees"."id" WHERE "fees "."deleted_at" 为空且 "fees"."instructor_id" = $1 => #
我应该如何编写手动加入费用和费用支付通知的查询?
【问题讨论】:
-
写成
@instructor.fee_payment_notifications.joins(:fees).select("fee_payment_notifications.*")。你写的是产生无效的 SQL。 Rails.select()没有被那样使用。 -
@ArupRakshit 它应该是
join(fee)也不起作用 -
Rails 有一个方法调用
.joins()而不是.join().. 新错误是什么?你有has_many :fees,所以它应该是joins(:fees)。 -
@ArupRakshit 是的,我的意思是 joins(:fee) 。我想通过付费通知加入费用,而不是让教师检查我更新的问题。