我的Rails应用中有三个模型,User
,Number
和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
迁移文件包含:
t.string :digits, index: true # Example: '14051234567' (no + sign)
在我的控制器中:
sort_mode = # asc or desc
@messages = current_user.messages.order(???)
问题是我想按他们的数字对这些邮件进行排序。
如何做到动态(取决于sort_mode)?
修改
sort_mode = 'asc'
@messages = current_user.messages.includes(:number)
order = { number: { digits: sort_mode } }
@messages = @messages.order(order)
^不起作用。第二个参数必须是方向。
,order('number.digits': sort_mode)
抛出:
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
答案 0 :(得分:8)
您需要使用includes
。尝试:
@messages = current_user.messages.includes(:number).order('numbers.digits ASC')