Reputation: 4117
Let's say I have the following in a rails4 app:
class Foo < AR::Base
has_many :foo_bar
has_many :bar, through: :foo_bar
end
And the foo_bar table has a "sort" column with a number. To make matters even more entertaining, the "bar" table ALSO has a "sort" column with a number. Same name as the join table sort column. AND, this is important...
class Bar < AR::Base
default_scope -> { order(:sort) }
end
I need to have a default scope on the association, such that:
foo = Foo.last
foo.bars # => List of bars, ordered by the number on the foo_bar table
How can I do this? It means unscoping the bar, but just the sort
Upvotes: 1
Views: 1536
Reputation: 4117
I got it to work by doing this:
class Foo < AR::Base
has_many :foo_bar
has_many :bar, through: :foo_bar
def sorted_bars
foo_bar.map(&:bar)
end
end
Because of the default scopes, this was too complicated for me. I'll still accept an answer that offers a more elegant solution :)
Upvotes: 0
Reputation: 1848
You can specify the sort order for collection using order
option
class Foo < AR::Base
has_many :foo_bar
has_many :bar, -> { order('foo_bar.sort') }, through: :foo_bar
end
Upvotes: 3
Reputation: 2762
You could do:
foo.bars.sort(foo_bar.position)
sort
will sort the list by a given attribute, so give it the attribute on foo_bar that you wish to sort by.
Upvotes: 0