【发布时间】: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