Rails not getting average using postgresql - ruby-on-rails

I'm working on learning Active Record and queries and wrote a query within my rails console that I thought should work pretty easily, but it is not.
Statistic.select("player_id, sum(oreb)").group("player_id").limit(5)
This returns the following Active Record Relation
[#<Statistic:0x007f801b2f0240 id: nil, player_id: 1>, #<Statistic:0x007f801b2f00b0 id: nil, player_id: 2>, #<Statistic:0x007f801fcffed0 id: nil, player_id: 3>, #<Statistic:0x007f801fcffd40 id: nil, player_id: 4>, #<Statistic:0x007f801fcffbb0 id: nil, player_id: 5>]
oreb does exist, i can use pgAdmin or the psql console tool to execute the query directly
Select player_id, sum(oreb) from Statistics
GROUP BY player_id
LIMIT 5
And get the a result that includes oreb.
I've done a bit of research, and can't find a simple reason for why this is not working...any thoughts would be appreciated...

Model Statistic doesn't have column for sum(oreb) and can't be mapped to model's attributes but data is retrieved. You can extract it by given name to sum.
stats = Statistic.select("player_id, sum(oreb) total").group("player_id").limit(5)
puts stats.first.total

Related

Rails Active Record: Missing column in group query

I saw that someone had the same question but the solution was not clear to me:
Rails ActiveRecord: Missing column in grouping query
I wrote a query in Active Record as follows:
shortened_urls.joins(:visits)
.group(:short_url, :long_url)
.select('long_url, short_url, COUNT(visits.id) as number_of_visits')
.order(Arel.sql('COUNT(visits.id) DESC'))
.limit(5)
And I get the following results:
[#<ShortenedUrl:0x00005585fbb8fb60
id: nil,
long_url: "jfjfhgfhduiuyyyyyyyyyyyyyyyyyyyyyyyyyy.k",
short_url: "Bn_N2QPoSE1VlNYqWXUL9A">,
#<ShortenedUrl:0x00005585fbb8f9f8
id: nil,
long_url:
"https://help.ubuntu.com/community/PostgreSQL#restarting_the_server",
short_url: "Dte6_CUnAdxJgv_jUBwXIg">,
#<ShortenedUrl:0x00005585fbb8f8b8
id: nil,
long_url: "jjjfhusirtyuizyfsvqdhjdhdfv",
short_url: "CQa8n1o-f2oEwKy8j_Zo9Q">,
#<ShortenedUrl:0x00005585fbb8f778
id: nil,
long_url: "uezfhueizyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy.kkkk",
short_url: "4S1uC8yl0a8HlK6xJq23FQ">,
#<ShortenedUrl:0x00005585fbb8f638
id: nil,
long_url: "blahffhhfhfhhfhfhffhfhhfhhfhfhfhfhhfhfh.com",
short_url: "_NZSroaeyvVqvOKoPAieng">]
As you can see, the column 'number_of_visits' doesn't appear and the id's are all nil;
Does anyone have any idea how to solve this ? Or maybe explain to me what was the solution for the other similar question posted?
Thank you very much

Trying to iterate over a activerecord to fetch the values

I am trying iterate through following active record
#<ActiveRecord::Relation [#<WantedEquipment id: 1, identifier: "WEID-0000001", title: "Wanted a Test Equipment", category_id: 1, sub_category_id: 3, listing_type: nil, description: "This is a test wanted equipment.", name: "John", email: "john.user#mailinator.com", user_id: nil, status: 1, created_at: "2017-02-25 16:10:35", updated_at: "2017-02-25 16:10:35">, #<WantedEquipment id: 2, identifier: "WEID-0000002", title: "Wanted a Test Equipment1", category_id: 1, sub_category_id: 3, listing_type: nil, description: "This is a test wanted equipment.", name: "John", email: "john.user#mailinator.com", user_id: nil, status: 1, created_at: "2017-02-25 16:10:50", updated_at: "2017-02-25 16:10:50">]>
To collect the values of column email. I am quiet new to ruby.
I ran the following on rails console.
WantedEquipment.all.each do |eq|
eq.email
end
As a result I got the whole table again instead of just the emails. Could somebody please guide me here?
If all you need are the email addresses and not the actual AR objects, then use this:
WantedEquipment.pluck(:email)
This will translate into the following SQL:
SELECT "wanted_equipments"."email" FROM "wanted_equipments"
You can select all email using following way
WantedEquipment.select('email')
If possible always use database level memory instead of system.
You can use either select or pluck here.
WantedEquipment.pluck(:email)
Or
WantedEquipment.select(:email)
Depends upon your result set performance you can use anyone.

Active Record Grouping in Ruby On Rails

record = #<ActiveRecord::AssociationRelation
[#<User id: 2, store_id: 3,location: 'xxx'>,
#<User id: 4, store_id: 3,location:'yyy'>,
#<User id: 5, store_id: 4,location:'zzz'>,
#<User id: 6, store_id: 4,location:'aaa'> ]>
How to group location in comma seperated form based on store_id in ruby to get the result as,
The location of store-id(3) should be combained with comma as (yyy,xxx),
then the location of store-id(4) should be combained with comma as (zzz,aaa)
#< store_id: 3,location:'yyy,xxx'>
#< store_id: 4,location:'zzz,aaa'>
Using Enumerable.group_by you can do it this way:
User.all.group_by(&:store_id).map{|store_id,records| {store_id: store_id, location: records.map(&:location).join(',')}}
If you want to do the grouping on database level, using the group method from ActiveRecord, it is required to have a function on the database that takes care of the concatenation, so the solution would depend on the database being used.
For example, in MySQL (see Can I concatenate multiple MySQL rows into one field?)
User.group("store_id").select("store_id, GROUP_CONCAT(location SEPARATOR ',') as location")

How would I get the names and id's out of this object?

I have an object called #groups
When I enter #groups into the console it returns this:
[#<Group id: 2, name: "another test group", creator_id: 6, updater_id: 6, created_at: "2013-11-22 17:04:14", updated_at: "2013-11-22 17:04:14">, #<Group id: 1, name: "test group", creator_id: 6, updater_id: 6, created_at: "2013-11-20 17:50:28", updated_at: "2013-11-20 17:50:28">]
I want to make an select field and populate it with each group using the options_for_select() method
So, I was going to try to get the names and id's of each group and populate it that way but I don't know how to do this.
Rather than mapping the attributes you want out of an array, you should do this the rails way by using either the options_from_collection_for_select or, even easier, you can use collection_select in your form.
You'll want to use map for this:
#groups.map {|group| [group.name, group.id]}
This will return an array of arrays, with each containing [group.name, group.id].

extract attributes values from an activerecord query object in rails 2.3

In my controller I have a #attach object and when I inspect it, it has values as
[#<MessageAddlAttachment id: 80, reminder_id: 112, msg_attachment_file_name: "24.png", msg_attachment_content_type: "image/png", msg_attachment_file_size: 272368, created_at: "2013-10-10 12:04:37", updated_at: "2013-10-10 12:04:37">, #<MessageAddlAttachment id: 81, reminder_id: 112, msg_attachment_file_name: "37.png", msg_attachment_content_type: "image/png", msg_attachment_file_size: 333986, created_at: "2013-10-10 12:04:37", updated_at: "2013-10-10 12:04:37">]
So now after some operation I need to create an entry in this MessageAddlAttachment table with different ids. How can I achieve it. I tried dup but it will have same ids. Please help
dup is your friend in rails 4. it will create a copy but removes the id value:
u = User.first
=> #<User id: 1, ...>
u.dup
=> #<User id: nil, ...>
u.dup.save
(0.2ms) begin transaction
...
Starting either rails 3.2 or 3.1, you want to use dup. Prior to that, you should use clone instead. That will give you new values for the id field; you might want to pay attention to what happens to your created_at and updated_at fields as well.
Another issue to watch out for is if you have any date fields with validations that say they must be after "today's date", they may have been valid when the original record was saved, but not when the new record is saved. How you resolve this will depend on your situation; you might want to disable validations completely while cloning, or adjust the values in the new records.

Resources