Mysql 对于两个不同的视图具有不同的数据库排序顺序(默认范围)

Mysql 对于两个不同的视图具有不同的数据库排序顺序(默认范围),mysql,sql,ruby-on-rails,ruby,sorting,Mysql,Sql,Ruby On Rails,Ruby,Sorting,在我的模型(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 这个排序顺序(如上)就是我希望我的“pins视图”(inde

在我的模型(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
这个排序顺序(如上)就是我希望我的“pins视图”(index.html.erb)的外观。这只是所有用户帖子的列表

在我的“用户视图”(show.html.erb)中,我使用相同的模型(pins.rb)只列出当前的用户pin。但是,我希望忽略“特色”默认范围,只使用第二个范围:

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'
并将“我的PIN”视图更新为:

<%= render @pins.featy %>

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

undefined method `featy' for #<Array:0x00000100ddbc78>
未定义的方法“featy”#

我建议考虑做以下事情:

引脚.rb

这将导致特征出现在列表的顶部,并根据它们创建的时间对它们进行二次排序。(注意按布尔值排序的两种方法)

PinsController.rb

class User < ActiveRecord::Base
  has_many :pins
end
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
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.featy
)时,实际上还没有从数据库中获取数据。这允许您链接更多范围(例如,
Pins.featy.wheaty


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

为什么不设置一个默认范围和另一个显式范围?请详细说明如何使用显式范围?我是新手,还没听说过。你是说我可以为某个视图或控制器定义一个显式的作用域@muistooshort,然后在不想使用默认范围时调用它。作用域实际上只是定义类方法的一种方式。@muistooshort谢谢,我接受了你的建议,但是现在我遇到了一个错误(请参阅我的更新)。你能发布一些代码吗?更具体地说,用户和pin上的关联定义。然后你的用户也会显示方法。这假设他正在调用
.all
,而他没有使用Rails 4。好吧,我想这只是一个例子,没有更多的代码很难看到。啊,但实际上,他不能使用Rails 4,因为他可以创建没有包装在
lambda
中的作用域。他可能在打电话给
。所有的
,但不一定。@MichaelLynch我打电话给你是对的。所有的(见更新)那么,你的解决方案应该有效吗?我可以试一试。如果我的User.rb中已经有:
有很多:pins,dependent::destroy
,我还需要包括:
有很多:最近的pins,顺序:'created_at DESC',类名:“pins”,source::pins
<%= @user.pins %>
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 %>