我在我的 Rails 应用程序中有一个主页视图,我也有两种类型的内容,文章和事件。我想在主页上有一个部分显示最近的文章和事件(混合,如新闻提要)。文章应按 created_at 排序,事件应按 start_date 排序。
我的问题是如何创建单个部分以在单个数组中显示两种类型的内容数组并正确排序它们?我是否创建一个方法并将其放在 home_controller 中来执行此操作?
谢谢
我在我的 Rails 应用程序中有一个主页视图,我也有两种类型的内容,文章和事件。我想在主页上有一个部分显示最近的文章和事件(混合,如新闻提要)。文章应按 created_at 排序,事件应按 start_date 排序。
我的问题是如何创建单个部分以在单个数组中显示两种类型的内容数组并正确排序它们?我是否创建一个方法并将其放在 home_controller 中来执行此操作?
谢谢
这就是合并结果和自定义搜索的粗略实现的方式。我没有测试搜索所以不能保证它有效。
@events = Events.all
@articles = Articles.all
@events_and_articles = (@events + @articles).sort { |a, b|
a_value = a.is_a?(Event) ? a.start_date : a.created_at
b_value = b.is_a?(Event) ? b.start_date : b.created_at
a_value <=> b_value
}
这可能不是最有效的,但我测试了它并且它有效。
def getstuff
stuff = Array.new
#Get the 10 most recent articles and add them to an array.
Article.order("created_at DESC").limit(10).each do |item|
stuff.push(item)
end
#Add the 10 most recent events to the same array
Event.order("start_date DESC").limit(10).each do |item|
stuff.push(item)
end
#Sort the array by the correct value based on the class.
stuff.sort_by! { |item|
item.class.name.eql?("Article") ? item["created_at"] : item["start_date"]
}
#Return the reverse of the sort result for the correct order.
return stuff.reverse!
end