Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

ruby on rails - Order products by association count

Class Product

has_many :sales

end

Class Sale

belongs_to :product

end

How do i get the most sold products.. (Product find all.. order by .. ventas..) ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You might want to hit two birds with one stone (the other bird being performance) by using a counter cache column in the product model. For instance, say you make a sale for product X. When that sale is committed to the database, it will run a callback to increase the number of sales for that product in the product's row in the database. When you destroy, it conversely decreases the number of products.

You'd need to set up a cache column in the products table. In a new migration, do this:

add_column :products, :sales_count, :integer, default => 0

Product.reset_column_information

Product.all.each do |product|
  Product.update_counters(product.id, :sales_count => product.sales.length
end

You'd also need to make some changes to your Product and Sale models, like this:

class Product < ActiveRecord::Base
  has_many :sales
end

class Sale < ActiveRecord::Base
  belongs_to :product, :counter_cache => true
end

Then, instead of having to load all of the sales associations (which, in a large app, would be treacherous), you'd just load the product, and you'd have the number of associated sales in the row itself, for a fraction of the cost of performance.

Hope this helps!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...