How to sort objects in a many-to-many relationship in ruby on rails?
Posted
by Kenji Kina
on Stack Overflow
See other posts from Stack Overflow
or by Kenji Kina
Published on 2010-05-14T02:39:53Z
Indexed on
2010/05/14
2:44 UTC
Read the original article
Hit count: 341
I've been trying to deal with this problem for a couple of hours now and haven't been able to come up with a clean solution. It seems I'm not too good with rails...
Anyway, I have the following:
In code:
class Article < ActiveRecord::Base
has_many :line_aspects, :dependent => :destroy
has_many :aspects, :through => :line_aspects
#plus a name field
end
class LineAspect < ActiveRecord::Base
belongs_to :article
belongs_to :aspect
end
class Aspect < ActiveRecord::Base
belongs_to :data_type
has_many :line_aspects
has_many :articles, :through => :line_aspects
end
Now, what I would like to do, is to sort these in two steps. First list of Articles by their Articles.name, and then inside sort them by Aspect.name (note, not the middleman).
For instance, alphabetically (sorry if the notation is not correct):
[{
article => 'Apple',
line_aspects => [
{:value => 'red'}, #corresponding to the Attribute with :name => 'color'
{:value => 'small'} #corresponding to the Attribute with :name => 'shape'
]
},{
article => 'Watermelon',
line_aspects => [
{:value => 'green'}, #corresponding to the Attribute with :name => 'color'
{:value => 'big'} #corresponding to the Attribute with :name => 'shape'
]
}]
Again, note that these are ordered by the aspect name (color before shape) instead of the specific values of each line (red before green).
(NOTE: My intention is to displaye these in a table in the view)
I have not found a good way to do this in rails yet (without resorting to N queries). Can anyone tell me a good way to do it?
© Stack Overflow or respective owner