2

我有一个包含很多内容的应用程序。现在我有一个布尔值叫做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

4

2 回答 2

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 中,TRUEs 保存为 't',FALSEs 保存为 '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”的列表中排序(上升)=> 如果特征为 TRUE,则返回“a”,否则返回“b”,然后在返回的字母列表中排序

希望这可以帮助!

于 2013-09-20T17:20:40.130 回答
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

这行得通。

于 2013-09-20T17:44:54.600 回答