How to order by in Rails?

情到浓时终转凉″ 提交于 2019-12-12 19:13:15

问题


I'm working on a small blog engine.

There are the following tables: Blog and Message.

Blog has a foreign key: last_message_id, so I access the last message in the blog by calling blog.last_message

I have the following code to make it work:

class Blog < ActiveRecord::Base  
  belongs_to :last_message, :class_name => "Message"
end

I need to order the blogs by the last messages. But when I call

blogs.order("last_message.created_at DESC")

It doesn't work. I get the following error:

PGError: ERROR:  missing FROM-clause entry for table "last_message"
ORDER BY  last_messa...

How can I make it work?

UPDATE

Here's the solution:

blogs.joins(:last_message).order("messages.created_at DESC").

回答1:


I think your model is wrong. See rails automaticly add 2 attributes to a model : created_at and update_at. So having a relationship like you describe is redondant. To me, it should look like this :

#model/blog.rb
class Blog < ActiveRecord::Base
  has_many :messages
end

#model/message.rb
class Message < ActiveRecord::Base
  belongs_to :blog
end

Then, to get the blogs ordered by the last message, you could do this :

Blog.joins(:messages).order("messages.created_at_desc")

That as you may have noticed will give you double entries for your blog model. If that is not a problem, go ahead. If it is, you have two options : doing a each and test if you already saw the blog - if not, you display it. Or, you could write your own sql.




回答2:


You have to make sure the last-messages are also selected to make that order-command work.\ So something like:

blogs.includes(:last_message).order("last_message.created_at desc")


来源:https://stackoverflow.com/questions/4122462/how-to-order-by-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!