【问题标题】:problem using default_scope on a model table在模型表上使用 default_scope 的问题
【发布时间】:2011-02-27 07:43:10
【问题描述】:

嘿。在我的控制器/索引操作中,我使用以下查询:

@course_enrollments = current_user.course_enrollments

这就是我的桌子的样子。它正在引用一个课程表。课程表有一个列“标题”。

create_table "course_enrollments", :force => true do |t|
  t.integer  "user_id",    :null => false
  t.integer  "course_id",  :null => false
  t.datetime "created_at"
  t.datetime "updated_at"
end

我希望能够在我的索引视图中按课程排序我的 course_enrollments。此外,我想在我的模型中做一个 default_scope,如下所示:

  default_scope :order => 'title asc'

有什么建议吗?谢谢你的时间

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord


    【解决方案1】:

    要对父模型进行排序,请按照Rails 3 sorting through parent association 的说明进行操作,即:

    CourseEnrollments.joins(:course).order('courses.title')
    

    对于默认范围,您应该能够使用:

    default_scope joins(:course).order('courses.title')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-24
      • 1970-01-01
      • 1970-01-01
      • 2015-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多