开发者

How to order by in Rails?

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").


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.


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")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜