Rails/ActiveRecord: Return order with ActiveRecord#find(Array)
By : Fabian Ortiz Padilla
Date : March 29 2020, 07:55 AM
I wish this helpful for you ActiveRecord is an interface to your database and returns the records to you in the same order that the database returns them. If you don't supply an 'order' parameter then the returned order is (effectively) random. If your order is by id ascending or descending: code :
results = SomeModelName.find([1,2,3], :order => "id") # ascending order
results = SomeModelName.find([1,2,3], :order => "id desc") # descending order
ids = [1, 3, 2]
r = SomeModelName.find(ids)
results = ids.map{|id| r.detect{|each| each.id == id}}
|
Group by with ActiveRecord in Rails
By : kC91
Date : March 29 2020, 07:55 AM
hop of those help? I have a the following table with rows: , I am assuming you want the following results: code :
group1_sum 2
group2_sum 1
group3_sum 1
group4_sum 4
gt = GroupTally.first(:select => "SUM(group1) AS group1,
SUM(group2) AS group2,
SUM(group3) AS group3,
SUM(group4) AS group4")
p gt.group1 # 2
p gt.group2 # 1
p gt.group3 # 1
p gt.group4 # 4
|
Rails 3 ActiveRecord: order and group by association count
By : MARE MARE
Date : March 29 2020, 07:55 AM
wish help you to fix your issue What you are looking for doesn't map well to standard ActiveRecord querying. You can call straight SQL to get what you are looking for most efficiently: code :
subquery = Song.joins(:listens).group(:id).select("songs.id, COUNT(*) as listen_count).to_sql
raw = Song.connection.select_rows("SELECT listen_count, COUNT(*) FROM (#{subquery}) t GROUP BY listen_count ORDER BY listen_count DESC")
song_listen_distribution = Hash[raw]
song_listens = Song.joins(:listens).group(:id).count
song_listen_distribution = song_listens.group_by{|n| n.last}.
each_with_object({}){|(k, g), h| h[k] = g.size}
|
Rails 4 activerecord group
By : user3571137
Date : March 29 2020, 07:55 AM
it helps some times I have an Order table and each order has a SOURCE and ORDER TOTAL. The source is basically were the order came from (Phone, Web, Ebay and so on). code :
Order.group(:source).sum(:order_total)
|
Rails ActiveRecord: group and order by count on association
By : Anandkmr144
Date : March 29 2020, 07:55 AM
seems to work fine I ended up doing a scope on music as fallows (surveys is a group of Survey for a given range of time): code :
scope :avrg, ->(surveys) { joins(:surveys).where("surveys_musics.survey_id in (?)", surveys).group("musics.id")
.order("count(surveys.id) desc").limit(1).first.name }
|