开发者

Rails Advanced Sorting

I have three models, basically:

class Vendor
  has_many :items
end

class Item
  has_many :sale_items
  belongs_to :vendor
end

class SaleItem
  belongs_to :item
end

Essentially, each sale_item points to a specific item (but has an associated quantity and sale price which might be different from the item's base price, hence the separate model), and each item is made by a specific 开发者_JS百科vendor.

I'd like to sort all sale_items by vendor name, but this means going through the associated item, because that's where the association is.

My first attempt was to change SaleItem to the following:

class SaleItem
  belongs_to :item
  has_one :vendor, :through => :item
end

Which allows me to look for SaleItem.first.vendor, but doesn't allow me to do something like:

SaleItem.joins(:vendor).all(:order => "vendors.name")

Is there an easy way to figure out these complex associations and sorting? It would be especially great if there were a plugin that could take care of these sort of things. I have a lot of different types of tables to add sorting to in this application, and I feel like this will be a big chunk of the figuring-out work.


This could definitely be done with a more complex SQL query (possibly using find_by_sql), but you could also do it pretty easily in Ruby. Try something like the following:

SaleItem.find(:all, :include => { :items => :vendors }).sort do |first,second|
  first.vendor.name <=> second.vendor.name
end

I haven't tested it, so it might not work exactly like this, but it should give you a good idea of one possible solution.

Edit: Found an old blog post that seems to have solved this issue. Hopefully this still works in the lastest version of ActiveRecord.

source: http://matthewman.net/2007/01/04/eager-loading-objects-in-a-rails-has_many-through-association/

Second Edit: Straight from the Rails documentation

To include a deep hierarchy of associations, use a hash:

for post in Post.find(:all, :include => [ :author, { :comments => { :author => :gravatar } } ])

That’ll grab not only all the comments but all their authors and gravatar pictures. You can mix and match symbols, arrays and hashes in any combination to describe the associations you want to load.

There's your explanation.


Do you really need your sale_items sorted by the database, or could you wait until it is presented and do the sorting client side via javascript (there are some great sorting libraries out there) - that would save server CPU and (backend) code complexity.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜