【问题标题】:Having different database sorting order (default_scope) for two different views对于两个不同的视图具有不同的数据库排序顺序 (default_scope)
【发布时间】:2013-11-15 21:21:52
【问题描述】:

在我的模型 (pins.rb) 中,我有两个排序顺序:

default_scope order: 'pins.featured DESC' #for adding featured posts to the top of a list
default_scope order: 'pins.created_at DESC' #for adding the remaining posts beneath the featured posts

这个排序顺序(上图)是我希望我的“引脚视图”(index.html.erb)的外观。这只是所有用户帖子的列表。

在我的“用户视图”(show.html.erb) 中,我使用相同的模型 (pins.rb) 来仅列出 current_user 引脚。但是,我想排序以忽略“特色”默认范围,只使用第二个范围:

default_scope order: 'pins.created_at DESC'

我怎样才能做到这一点?我试着做这样的事情:

default_scope order: 'pins.featured DESC', only: :index
default_scope order: 'pins.created_at DESC'

但这并没有成功......

更新

我更新了模型以定义范围:

scope :featy,  order: 'pins.featured DESC'
default_scope order: 'pins.created_at DESC'

并将我的图钉视图更新为:

<%= render @pins.featy %>

但是,现在当我打开我的 pin 视图时,我得到了错误:

undefined method `featy' for #<Array:0x00000100ddbc78>

【问题讨论】:

  • 为什么没有一个默认作用域和另一个显式作用域?
  • 您能否详细说明使用显式范围?我是新手,还没有听说过。所以你是说我可以为某个视图或控制器有一个明确的范围? @muistooshort
  • Define a scope 然后在您不想使用默认范围时调用它。范围实际上只是定义类方法的一种方式。
  • @muistooshort 谢谢,我采纳了你的建议,但是现在我遇到了一个错误(请参阅我的更新)
  • 你能发布一些你的代码吗?更具体地说,用户和 pin 的关联定义。然后还有你的用户显示方法。

标签: mysql sql ruby-on-rails ruby sorting


【解决方案1】:

我建议考虑执行以下操作:

Pins.rb

这将导致该功能位于列表顶部,其中的次要排序按创建时间排序。 (注意布尔排序的两种方法)

class Pin < ActiveRecord::Base
  belongs_to :user

  default_scope  order: 'created_at DESC'
  # Method 1      
  scope :featy,  order('featured DESC, created_at DESC')
  # Method 2
  # scope :featy,  order('(case when featured then 1 else 0 end) DESC, created_at DESC')
end

用户.rb

class User < ActiveRecord::Base
  has_many :pins
end

UsersController.rb

class UsersController < ApplicationController
  def show
    @user = User.find(params[:id])
    # Pins are accessed via: @user.pins
    # These should be sorted by `created_at DESC` as that is the default_scope
  end
end

users/show.html.erb这是按created_at desc排序的所有用户pin

<%= @user.pins %>

PinsController.rb

class UsersController < ApplicationController
  def index
    # Pins sorted by created_at: @pins = Pin.all
    # Pins sorted by created_at with all featured on top: 
    @pins = Pin.featy
  end
end

pins/index.html.erb: 这是按created_at desc 排序的所有图钉,所有图钉都在顶部

<%= @pins %>

【讨论】:

  • 这假设他正在调用 .all 并且他没有使用 Rails 4。
  • 好吧,我想这只是一个例子,没有更多代码很难看到。
  • 啊,但实际上,他不能使用 Rails 4,因为他可以创建未包含在 lambdas 中的范围。那时他可能会打电话给.all,但不一定。
  • @MichaelLynch 你说得对,我打电话给 .all (见更新)那么,你的解决方案应该有效吗?我可以试一试。
  • 如果我的 User.rb 中已经有:has_many :pins, dependent: :destroy,我还需要包括:has_many :recent_pins, order: 'created_at DESC', class_name: "Pins", source: :pins 吗?
【解决方案2】:

在 Active Record 中,直到需要时才执行对数据库的查询。当您调用模型上的范围时(例如Pins.featy),您实际上还没有从数据库中获取数据。这允许您链接更多范围(例如Pins.featy.wheaty)。

很可能,您正在对@pins 执行某些操作以强制它从数据库中获取。您能分享一下您在控制器中所做的事情吗?

【讨论】:

    猜你喜欢
    • 2014-02-21
    • 2014-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-21
    • 1970-01-01
    • 2016-05-22
    相关资源
    最近更新 更多