Rails Active Record: find in conjunction with :order and :group
From your models, all association info has already been declared. You can actually use each of user to access dongles and licences info by performing a single query with ActiveRecord include options.
# Say the table name is licences and dongles.
users = User.find(:all,
:include => [:dongles, :licences],
:order => "licences.created_at DESC, dongles.created_at DESC")
I assume you want to create a summary of latest licence of each dongle owned by each user. You may cut the loop upon your actual needs.
users.each do |user|
# do something with your user info
user.dongles.each do |dongle|
# do something with your dongle info
licence = dongle.licences.first
# do something with the licence info
end
end
Read more about this at http://snippets.dzone.com/posts/show/2089
Issues with DISTINCT when used in conjunction with ORDER
If you're on Ruby 1.9.2+, you can use Array#uniq
and pass a block specifying how to determine uniqueness. For example:
@unique_results = @filtered_names.uniq { |result| result.athlete_id }
That should return only one result per athlete, and that one result should be the first in the array, which in turn will be the quickest time since you've already ordered the results.
One caveat: @filtered_names
might still be an ActiveRecord::Relation
, which has its own #uniq
method. You may first need to call #all
to return an Array of the results:
@unique_results = @filtered_names.all.uniq { ... }
How to sort a list of value in ruby on rails?
You can use Active Record Query Interface this way .
Student.order("name ASC") # Returns all students sorted in ascending order by name
Student.find(:all, :order => "age DESC") # Returns all students sorted by age in descending order
Check this out for finding and sorting nested models. Rails Active Record: find in conjunction with :order and :group
How to display unique records from a has_many through relationship?
Have you tried to specify the :uniq option on the has_many association:
has_many :products, :through => :orders, :uniq => true
From the Rails documentation:
:uniq
If true, duplicates will be omitted from the collection. Useful in conjunction with :through.
UPDATE FOR RAILS 4:
In Rails 4, has_many :products, :through => :orders, :uniq => true
is deprecated. Instead, you should now write has_many :products, -> { distinct }, through: :orders
. See the distinct section for has_many: :through relationships on the ActiveRecord Associations documentation for more information. Thanks to Kurt Mueller for pointing this out in his comment.
Select records with highest values for each subset
You could use something like this by using 2 subqueries (will do only one SQL query which has subqueries). Did not test, but should get you in the right direction. This is for Postgres.
scope :null_ids, -> { where(path: nil).select('id') }
scope :non_null_ids, -> { where('path IS NOT NULL').select('DISTINCT ON (path) id').order('path, value desc, id') }
scope :stuff, -> {
subquery = [null_ids, non_null_ids].map{|q| "(#{q.to_sql})"}.join(' UNION ')
where("#{table_name}.id IN (#{subquery})")
}
If you are using a different DB you might need to use group/order instead of distinct on for the non_nulls scope. If the query is running slow put an index on path and value.
You get only 1 query and it's a chainable scope.
Get top results by SUM column in Rails
This should work
SectionInput.select([:main_section_id, :district_id, 'sum(answer) as total']).where(:year=>2012).where(:main_section_id=>2).group(:main_section_id).group(:district_id).order('3 desc').limit(5)
Else, you can directly include the sql to run
SectionInput.find_all_by_sql('select main_section_id, district_id,
sum(answer) from section_inputs where year = 2012 and main_section_id=
2 group by main_section_id, district_id order by 3 desc limit 5')
Also, look at the guide to see all Rails 3 querying basics
Related Topics
How to Programmatically Check If a Certificate Has Been Revoked
Array Typeerror: Can't Convert Fixnum into String
Ruby - Does Array a Contain All Elements of Array B
Ruby on Rails: How to Use Oauth2::Accesstoken.Post
Rails How to Change Attribute Name When Rendering JSON
Rails: How to Print a Decimal as a Percent
Ruby: What Is the Order of Keys/Values Returned by Hash.Keys and Hash.Values Methods
Simple Conversion of String to Utf-8 in Ruby 1.8
Ruby Variable as Same Object (Pointers)
Documentation for Psych To_Yaml Options
Configure Webrick to Use Automatically Generated Self-Signed Ssl/Https Certificate
How to Integrate 'Premailer' with Rails
How to Render a String as an Erb File
How to Use Escape Characters in Strings