从按共享列排序的多个表中获取记录
Get records from multiple tables ordered by shared column
我是 rails 的新手,我不知道如何进行这个简单的操作:
我有,
class Section < ActiveRecord::Base
has_many :articles
has_many :questions
end
class Article < ActiveRecord::Base
belongs_to :section
end
class Question < ActiveRecord::Base
belongs_to :section
end
我想获取某个部分下的所有文章和问题,但按共享列 'updated_at' 排序在一起。
我尝试包括并加入他们,但没能一起订购。
一旦结果在单个数组中,您可以执行以下操作:
@sorted = @records.sort_by &:updated_at
首先找到您希望使用的部分。例如,您可以按 ID(在本例中为 12)查找特定部分:
section = Section.find(12)
然后您可以访问属于该部分的文章和问题,并将结果与 +
运算符组合:
articles_and_questions = section.articles + section.questions
articles_and_questions
变量属于 ActiveRecord::Associations::CollectionProxy
. Because the @target
s of section.articles
and section.questions
are both Array
s of objects, you can call any method from the Array
class on articles_and_questions
. In this case, you can use sort_by
which comes from the Enumerable
模块类型,包含在 Array
:
sorted_articles_and_questions = articles_and_questions.sort_by &:updated_at
如果您想知道为什么 &:updated_at
中有一个 & 符号,请阅读 this。
我是 rails 的新手,我不知道如何进行这个简单的操作:
我有,
class Section < ActiveRecord::Base
has_many :articles
has_many :questions
end
class Article < ActiveRecord::Base
belongs_to :section
end
class Question < ActiveRecord::Base
belongs_to :section
end
我想获取某个部分下的所有文章和问题,但按共享列 'updated_at' 排序在一起。
我尝试包括并加入他们,但没能一起订购。
一旦结果在单个数组中,您可以执行以下操作:
@sorted = @records.sort_by &:updated_at
首先找到您希望使用的部分。例如,您可以按 ID(在本例中为 12)查找特定部分:
section = Section.find(12)
然后您可以访问属于该部分的文章和问题,并将结果与 +
运算符组合:
articles_and_questions = section.articles + section.questions
articles_and_questions
变量属于 ActiveRecord::Associations::CollectionProxy
. Because the @target
s of section.articles
and section.questions
are both Array
s of objects, you can call any method from the Array
class on articles_and_questions
. In this case, you can use sort_by
which comes from the Enumerable
模块类型,包含在 Array
:
sorted_articles_and_questions = articles_and_questions.sort_by &:updated_at
如果您想知道为什么 &:updated_at
中有一个 & 符号,请阅读 this。