1
class Foo < ActiveRecord::Base
  has_many :bar
end

class Bar < ActiveRecord::Base
  belongs_to :foo
end

I'd like to order my :foos... based on its last :bar

So, let's say:

Foo.first.bars => [{key: 'a', value: 1}, {key: 'b', value: 2}, {key: 'c', value: 3}]

So... Foo.first.bars.last.value => 3

I have a bunch of :foos, each having a bunch of :bars, but I only care about the last :bar.

Can I sort my :foos based on its last :bars value? Would Bar need a scope?

For instance...

Foo.includes(:bars).order('bars.last.value')
Dudo
  • 4,002
  • 8
  • 32
  • 57
  • It's not clear what you're trying to do. – smathy Feb 20 '15 at 03:00
  • I have a table of :foos. I want to be able to sort them based on the value of each :foo's last :bar. I'm positive a scope will work somewhere, but I haven't figured it out yet. I can achieve what I'm after by using enumerable... `Foo.all.sort_by(&:some_method)` where `some_method` is calculating the last :bar's `value`. Does that clear it up? – Dudo Feb 20 '15 at 03:06
  • my problem is, enumerable is slow... – Dudo Feb 20 '15 at 03:08
  • 1
    does something like this help -- http://stackoverflow.com/questions/9197649/rails-sort-by-join-table-data – Doon Feb 20 '15 at 03:18

1 Answers1

1
class Foo < ActiveRecord::Base
  has_many :bar
  scope :latest_foo_value, ->(ord) { includes(:foos).order("foos.value #{ord.upcase}") }
end

class Bar < ActiveRecord::Base
  belongs_to :foo
  default_scope order: 'created_at DESC'
end

Thanks, @Doon! If you wanna copy and paste this into your own answer, I'll gladly give you credit. Do you know if there's a way to call a named scope on Bar? Something like:

class Foo < ActiveRecord::Base
  has_many :bar
  scope :latest_foo_value, ->(ord) { includes(:foos).order("foos.current.value #{ord.upcase}") }
end

class Bar < ActiveRecord::Base
  belongs_to :foo
  scope :current, -> { order('created_at DESC') }
end

That doesn't work... Mysql2::Error: Unknown column 'foos.current.value' in 'order clause'.

Cheers!

Dudo
  • 4,002
  • 8
  • 32
  • 57