如何首先显示特色内容,然后在范围内显示其余内容?

时间:2013-09-20 17:15:56

标签: ruby-on-rails

我有一个内容很多的应用。现在我有一个名为featured的布尔值。标记为feature时,我希望此内容显示在页面顶部。现在,我对内容有一个范围顺序,但我不确定如何首先显示特色项目。有什么想法吗?以下是我对内容的小范围:

  scope :published, where(:published => true )
  scope :unpublished, where(:published => false )
  scope :ordering, order("published_date desc")
  scope :feature, where(feature: true )

以下是我的家庭控制器显示内容的内容:

  def index
    @contents = Content.includes(:author).published.ordering
    @collections = @user.try(:collections)
    @categories = Category.includes(:subcategories).all
  end

似乎有一种比if else语句更好的方法。建议?我一直在查看订单文档,没有找到针对此案例的具体内容。

使用:
Rails 3.2.14
Ruby 1.9.3

2 个答案:

答案 0 :(得分:1)

您可以在顺序中使用SQL CASE WHEN子句来定义特定属性值的特定行为:

scope :ordered_by_featured_then_published, order("CASE contents.featured = 't' THEN 'a' ELSE 'b' END ASC, contents.published_date DESC")
# for readability, content of the order method:
# "CASE contents.featured = 't' THEN 'a' ELSE 'b' END ASC, contents.published_date DESC"

这个SQL CASE WHEN适用于PostGreSQL。您可能必须在此处进行一些语法更改,但您有了这个概念。

并以这种方式使用:

@contents = Content.includes(:author).published.ordered_by_featured_then_published

一些解释:

  • content.featured = 't'”=>这将测试content.featured = TRUE的值(在PostGreSQL,TRUE中的值是否保存为't',FALSE是否为'f')
  • CASE contents.featured = 't' THEN 'a' ELSE 'b' END”=>如果features为TRUE,则返回字母'a',否则返回'b'
  • ORDER BY CASE contents.featured = 't' THEN 'a' ELSE 'b' END ASC”:根据上述声明,我们在“a”和“b”=>列表中命令(上升)如果features为TRUE,则返回“a”else返回“b”,然后按返回的字母列表
  • 排序

希望这有帮助!

答案 1 :(得分:1)

scope :order_by_feature_then_published, order("contents.feature DESC").order("published_date DESC")


  def index
    @contents = Content.includes(:author).published.order_by_feature_then_published
    @collections = @user.try(:collections)
    @categories = Category.includes(:subcategories).all
  end

这很有效。