【问题标题】:Sorting scope by boolean values (rails model)按布尔值排序范围(rails 模型)
【发布时间】:2013-11-07 12:32:39
【问题描述】:

我有两个从 Pins 模型生成的视图(用户/显示和引脚/索引)。

在 users/show 上,我想使用默认范围来显示所有引脚。 在引脚/索引上,我想使用 features_order 范围在顶部显示“特色”引脚,然后继续使用默认范围。

这就是我所拥有的,但由于某种原因,它正在恢复到所有内容的默认范围。

class Pin < ActiveRecord::Base
  attr_accessible :content, :title

  belongs_to :user

  # for sorting featured and newest pins first
  default_scope order: 'created_at DESC'
  scope :featured_order, order('(case when featured then 1 else 0 end) DESC, created_at DESC')
end

在我的 index.html.erb 中,我渲染了一个部分 (_pin.html.erb):

<%= render @pins %>

在我的 show.html.erb 中有一个列表:

<% @pins.each do |pin| %>
    <%= pin.title %>
    <%= pin.content %>
<% end %>

【问题讨论】:

    标签: ruby-on-rails ruby sorting scope boolean


    【解决方案1】:

    在索引控制器中

    @pins = Pin.featured_order 
    

    然后你可以迭代它。 这将按特色顺序排序,并在需要时使用 default_scope。

    如果这不起作用,您最好创建范围并根据需要使用而不是默认范围。

    我总是在使用 default scope 方面犯错。

    【讨论】:

    • 你说得对,default_scope 接管了一切。所以我最终删除了它并为用户/节目创建了一个单独的范围
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多