如何在Rails中进行排序? [英] How to order by in Rails?
问题描述
有以下表格:Blog和Message。
博客有一个外键:last_message_id,所以我通过调用blog.last_message来访问博客中的最后一条消息。
我有下面的代码来使它工作:
class Blog< ActiveRecord :: Base
belongs_to:last_message,:class_name => Message
end
我需要通过最后一条消息来订购博客。但是当我打电话给
$ $ p $ code> blogs.order(last_message.created_at DESC)
不起作用。我得到以下错误:
pre $ PGError:错误:缺少表last_message的FROM子句条目
ORDER BY last_messa ...
如何让它工作?
$ b $ p $ blogs.joins(:last_message).order(messages.created_at DESC)。
我认为你的模型是错误的。请参阅rails自动将2个属性添加到模型: created_at
和 update_at
。所以有一个像你描述的关系redondant。对我来说,它应该是这样的:
#model / blog.rb
class Blog< ActiveRecord :: Base
has_many:messages
end
#model / message.rb
class Message< ActiveRecord :: Base
belongs_to:blog
end
然后,博客订购的最后一条消息,你可以这样做:
Blog.joins(:messages).order(messages.created_at_desc )
正如您可能已经注意到的那样,会为您的博客模型提供两倍的条目。如果这不是问题,请继续。如果是这样,你有两个选择:做一个每个
并测试你是否已经看到博客 - 如果没有,你显示它。或者,你可以写你自己的SQL。
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.
这篇关于如何在Rails中进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!