新手问题 ruby-china 源码疑惑

itsvoid · 2012年11月12日 · 最后由 itsvoid 回复于 2012年11月12日 · 2622 次阅读

在 notification controller 的源码里面:

@notifications = current_user.notifications.recent.paginate :page => params[:page], :per_page => 20

其中这个 recent,我在 Notification::Base 里面没有发现有这个 scope 呢?难道是Mongoid::BaseModel里面自带的?

我确实是在Mongoid::BaseModel里面找到了这个 recent,但是我直接在我自己的一个类似的 notification.rb 里面直接写一个 recent scope 怎么不起作用呢,我的意思是,必须要写在 mongoid 里面?

#1 楼 @itsvoid 不会啊,你把代码贴出来看看。

#2 楼 @Rei 我有一个节点

def index
        @selected_node = Node.first
        @custom_search_engines = @selected_node.custom_search_engines.recent.compact
        @topics = @selected_node.topics
        render 'layout'
    end

里面用到了@selected_node.custom_search_engines.recent

在 CustomSearchEngine 这个 model 里面定义了一个 scope: scope :recent, desc(:created_at)

而 Node 和 CustomSearchEngine 两者的关系就是 has_many 和 blongs_to。

求解。。。

first 不是 scope,会查数据库。

scope 不是用来排序的吧。

我理解就是一个 where 条件,DRY。

#3 楼 @itsvoid has_many 正常来说是可以接着用 scope 的,再把 model 代码贴出来看看?以及报了什么错误?

#7 楼 @Rei 谢谢各位的热心回复。我已经找到原因了。是我在做分页的 view 文件里面,直接用的类 CustomSearchEngine.page,而不是@selected_node.custom_search_engines.recent

需要 登录 后方可回复, 如果你还没有账号请 注册新账号