ActiveRecord查询(包括或联接)

时间:2019-03-14 01:33:56

标签: ruby-on-rails ruby postgresql rails-activerecord

我有两节课:

class Customer 
    has_many :packages
end

class Package 
    belongs_to :customer
end

如何进行这样的查询?

Customer.includes(:packages).where(packages: 'expires_at < Date.current')

通过控制台的示例测试,我得到了:Customer Load (26.0ms) SELECT "customers".* FROM "customers" INNER JOIN "packages" ON "packages"."customer_id" = "customers"."id" WHERE (packages.expires_at < '2019-03-13') LIMIT $1 [["LIMIT", 11]] Traceback (most recent call last): ActiveRecord::StatementInvalid (PG::UndefinedFunction: ERROR: operator does not exist: integer = uuid) LINE 1: ...INNER JOIN "packages" ON "packages"."customer_id" = "custome... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. : SELECT "customers".* FROM "customers" INNER JOIN "packages" ON "packages"."customer_id" = "customers"."id" WHERE (packages.expires_at < '2019-03-13') LIMIT $1 irb(main):003:0>

4 个答案:

答案 0 :(得分:2)

您可以在引号内传递where表达式,并为expires_at绑定值。

for file in os.listdir('csv/'):

    filename = 'csv/{}'.format(file)

    print(filename)

    df = pd.read_table(filename,skiprows=3,sep=';')

    df1=df.loc[(df['#timestamp'] <= 0) & (df['#timestamp'] >=-5)]

答案 1 :(得分:1)

您可以这样做:

Customer.includes(:packages).where('packages.expires_at < ?', Date.current).references(:packages)

答案 2 :(得分:1)

Customer.joins(:packages).where("packages.expires_at < CURRENT_DATE")

Customer.includes(:packages).where("packages.expires_at < CURRENT_DATE").references(:packages)

答案 3 :(得分:0)

您可以执行以下操作:

Customer.includes([:packages]).where(["packages.expires_at < ?', Date.today]).references(:packages).order("Customers.created_at desc")