missing attributes name in rails association - ruby-on-rails

I have the following query in my rails app but its result does not have attributes name so I am not able to use it in amcharts
EmployeeDepartment.joins(:states).group
("employee_departments.name").count
the result is : {"Academic Support":1}
how to make it like this {"department_name":"Academic Support","department_count":1}

Let's say you have a hash like this:
hash = { "Academic Support" => 1, "Another Department" => 3, "Something Else" => 4 }
You can just use map to transform it into an array of hashes containing what you need.
hash.map { |k, v| { "department_name" => k, "department_count" => v } }
=> [{"department_name"=>"Academic Support", "department_count"=>1},
{"department_name"=>"Another Department", "department_count"=>3},
{"department_name"=>"Something Else", "department_count"=>4}]
If your hash only ever contains one key/value pair and you just want another hash, you could try this:
Hash[[["department_name", "department_count"], hash.first].transpose]
Or even simpler...
{ "department_name" => hash.keys.first, "department_count" => hash.values.first }

I solved my problem by this steps:
the following code:
EmployeeDepartment.joins(:states).group
("employee_departments.name").count
generates this in rails console
SELECT COUNT(*) AS count_all, employee_departments.name AS employee_departments_name FROM "employee_departments" INNER JOIN "tickets" ON "tickets"."employee_department_id" = "employee_departments"."id" INNER JOIN "states" ON "states"."id" = "tickets"."state_id" GROUP BY employee_departments.name
i used what was generated in the console in the following:
#department_count = EmployeeDepartment.find(:all,
:select => 'employee_departments.name AS employee_departments_name, COUNT(*) AS department_counter',
:joins => 'INNER JOIN tickets ON tickets.employee_department_id = employee_departments.id INNER JOIN states ON states.id = tickets.state_id',
:group => 'employee_departments.name')
Now the result in amcharts is:
var chartData = [{"department_counter":1,"employee_departments_name":"Academic Support"}];

Related

Ruby on Rails get unique country from Query results

Following were my query to get list of products:
#listed_products = #products.where(:step => 5, :status => 1)
.includes(:product_attachments)
.includes(:product_reviews)
.order("created_at desc")
The result return products which also consist many similar country eg:
name:prod1
city:city1
country:A
name:prod2
city:city3
country:A
name:prod3
city:city5
country:B
How can I filter out just unique country A,B from the result query? I just need country list to build a drop down list for user to sort product based on country. Thanks!!
You can try this -
#listed_products = #products.where(:step => 5, :status => 1)
.includes(:product_attachments)
.includes(:product_reviews)
.order("products.created_at desc")
result = #listed_products.pluck(:country).uniq
Try the below code:
#listed_products = #products.where(:step => 5, :status => 1)
.includes(:product_attachments)
.includes(:product_reviews)
.order("created_at desc").uniq.pluck(:country)

Rails scope returns duplicates

I have a Rails scope query that is returning duplicates. Can anyone see what's the problem with it?
Here's the code:
scope :visible_to_user, lambda { |user|
{
:joins => 'LEFT JOIN SCHEMA.groups ON groups.id = uploaded_files.group_id
LEFT JOIN uploaded_file_references ON uploaded_files.id = uploaded_file_references.uploaded_file_id
LEFT JOIN message_threads ON message_threads.id = uploaded_file_references.thread_id
LEFT JOIN thread_participants ON thread_participants.message_thread_id = message_threads.id',
:conditions => [
%{
uploaded_files.in_private_conversation = false
AND ( ( NOT COALESCE(groups.private, false) )
OR uploaded_files.group_id IN (?)
OR ( thread_participants.referenced_id = '?'
AND thread_participants.referenced_type = 'User')
)
}, user.group_ids, user.id
]
}
}
In rails >= 3:
You can add .uniq call to any scope to not return duplicates, like so:
MyTable.a_scope.where(something).uniq
In rails < 3:
you have to add it by hand with a select configuration like so:
MyTable.find(:all, :select => "distinct my_table.*")

ActiveRecord: PostgreSQL-specific update with join

The line like this (split into multiple lines for readability):
ValueMapping
.joins(:variation)
.where(
:mapper_id => 1,
:variations => {:name => 'de'}
)
.update_all(:value => 'Beispiel')
produces following SQL statement:
UPDATE value_mappings
SET value = 'Beispiel'
WHERE value_mappings.id IN (
SELECT value_mappings.id
FROM
value_mappings
INNER JOIN variations ON variations.id = value_mappings.variation_id
WHERE
value_mappings.mapper_id = 1
AND variations.name = 'de'
)
But I would like to get more PostgreSQL-specific request:
UPDATE value_mappings
SET value = 'Beispiel'
FROM
variations
WHERE
variations.id = value_mappings.variation_id
AND value_mappings.mapper_id = 1
AND variations.name = 'de'
)
Is it possible with ActiveRecord?

sql distinct statement and use of more than one table on rails

How would you write this line in the "rails way"?
unique_attendees = CourseSessionsUser.count_by_sql(["SELECT count(DISTINCT csu.user_id) AS count_user_id FROM course_sessions_users csu, course_sessions cs WHERE cs.course_id = ? AND csu.course_session_id = cs.id"], #course.id)
The query itself is:
SELECT count(DISTINCT csu.user_id) AS count_user_id
FROM course_sessions_users csu,
course_sessions cs
WHERE cs.course_id = ?
AND csu.course_session_id = cs.id
Use count method of the rails
count = CourseSessionsUser.count('csu.user_id',
:distinct => true, :conditions => ["cs.course_id = ?", #course.id]
:joins => "cs LEFT JOIN course_sessions_users csu ON cs.id = csu.course_session_id")
This will return directly non zero integer if condition matches otherwise return zero

Group by in Rails View

In my rails application I have following models
Transaction
belongs_to :account
belongs_to :agent
belongs_to :program
And here is the query i used to get data
def self.efficiency_report(starts=nil, ends=nil)
sql = "SELECT p.abbreviation,ag.name,
t.miles, t.date
FROM transactions t
inner join accounts a on t.account_id = a.id
inner join programs p on a.program_id = p.id
inner join agents ag on t.agent_id = ag.id
Group by p.id , ag.id"
result_array(sql)
end
def self.result_array(sql)
conn = ActiveRecord::Base.connection
res = conn.execute(sql)
results = []
res.each{|r|
results << r
}
return results
end
I want to render data in view with group by program first then group by agent name under it then miles, like this
Program:AA
Agent:Bob
Miles Date
1234 02/12/2012
5463 03/12/2012
Agent:Ben
Miles Date
234 02/22/2012
344 01/02/2012
Program:BB
Agent:Bob
Miles Date
1234 02/12/2012
5463 03/12/2012
Agent:Ben
Miles Date
234 02/22/2012
344 01/02/2012
For this i m doing following in my view
%h2 Vendor Efficiency Report
- #transactions.group_by(&:row[0]).sort.each { |data, transaction|
%h2= data.row[0]
- transaction.group_by(&:row[1]).sort.each { |data, transaction|
%table#data_table.display{:cellpadding => "0", :cellspacing => "0"}
%h3{:style => "clear:both;margin-left:10px"}= data.row[1]
%thead
%tr.odd
%td.bold{:style => "width:60px;"} Miles
%td.bold{:style => "width:60px;"} Date
- for t in transaction
%tbody
%tr
%td{:style => "width:60px;"}= row[2]
%td{:style => "width:60px;"}= row[3]
-}
-}
= will_paginate #transactions
But i m getting this error
wrong argument type String (expected Proc)
Will anyone let me know what i m doing wrong here or is there any other better way for grouping?
Thanks in advance
The problem is your group_by calls. I'm not sure what &:row[0] is doing, but it's passing a string as argument. I think this is what you're looking for:
#transactions.group_by{ |r| r[0] }...
Edit
Just figured out what &:row[0] was doing. It's a call to the Symbol#[] method, which returns the character at the index given (essentially, as if it were aString). The call :row[0] returns the first character of the string "row".
So basically, it was as if you were calling:
#transactions.group_by(&"r")

Resources