简体   繁体   中英

No result for select sum query using ActiveRecord (bigint column)

I have a table called banners with a column id (bigint) and click (bigint) and user_id (bigint)

In the console, or even the controller when I use the following request :

Banner.select("sum(click) as clicks").where(user_id: 5)

I get :

 => #<ActiveRecord::Relation [#<Banner id: nil>]>

I copied the same resulting request in phppgadmin SQL :

SELECT  sum(click) as clicks FROM "banners" WHERE "banners"."user_id" = 5

and it works, but with active record it does not !!?

Rails version : 5.1.4

UPDATE

I tried Banner.select("sum(id)") and it gives me => #<ActiveRecord::Relation [#<Banner id: nil>]>

With users table : User.select("sum(id)") it gives : => #<ActiveRecord::Relation [#<User id: nil, sum: 0.1e1>]>

It's weird as it works for one table and not others... I even switched to another project and tried different tables, I get the same behavior.

Try with adding group clause on id.

Banner.select("sum(click) as clicks").where(user_id: 5).group(:id)

It will return ActiveRecord::Relation [#<Banner id: nil>, #<Banner id: nil> and now when you call .first.clicks on this will give you desired output (sum of clicks). If you want id's as well you will have to specify id in select clause.

If

banners = Banner.select("sum(click) as clicks").where(user_id: 5)

banners.class will be Banner:ActiveRecord_Relation , In order to fetch clicks you have to use .first or .last (As it will have only one element in it), like following

banners.last.clicks

You can verify it by using

Banner.where(user_id: 5).sum(:click)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM