Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails order by a field in parent belongs_to association

I have three models in my Rails app, User, Number, and Message:

class User < ActiveRecord::Base
  has_many :numbers
  has_many :messages, through: :numbers
end

class Number < ActiveRecord::Base
  belongs_to :user
  has_many :messages
end

class Message < ActiveRecord::Base
  belongs_to :number
end

Number migration file has:

t.string :digits, index: true # Example: '14051234567' (no + sign)

In my controller:

sort_mode = # asc or desc
@messages = current_user.messages.order(???)

The thing is that I want to sort those messages by their numbers' digits.

How to do that dynamically (depending on sort_mode)?

EDIT:

sort_mode = 'asc'
@messages = current_user.messages.includes(:number)
order = { number: { digits: sort_mode } }
@messages = @messages.order(order)

^ Doesn't work. Second argument must be a direction.

Also, order('number.digits': sort_mode) throws:

SQLite3::SQLException: no such column: messages.number.digits: SELECT  "messages".* FROM "messages" INNER JOIN "numbers" ON "messages"."number_id" = "numbers"."id" WHERE "numbers"."user_id" = ?  ORDER BY "messages"."number.digits" ASC LIMIT 10 OFFSET 0
like image 599
Vlad Faust Avatar asked Oct 05 '15 19:10

Vlad Faust


1 Answers

You'll need to use includes. Try:

@messages = current_user.messages.includes(:number).order('numbers.digits ASC')
like image 51
Sean Huber Avatar answered Nov 03 '22 07:11

Sean Huber