【问题标题】:Multi-layer sorting in Rails modelRails 模型中的多层排序
【发布时间】:2013-02-03 17:58:50
【问题描述】:

我无法弄清楚如何在我的模型中使用范围方法编写多层排序,该方法可以对模型的属性及其相关子模型的属性进行排序?

更具体地说,我有以下模型,每个模型都是前一个模型的相关子代(为简洁起见,我排除了其他模型方法和声明):

class Course < ActiveRecord::Base 
  has_many :questions
  # would like to write multi-layer sort here 
end 

class Question < ActiveRecord::Base 
  belongs_to :course, :counter_cache => true
  has_many: :answers

end 

class Answer < ActiveRecord::Base 
  belongs_to :question, :counter_cache => true
end

我想先按questions_count(通过我的counter_cache)对课程进行排序,然后answer_count,最后按created_at,我想知道如何将所有内容都串起来一起放入单个范围方法中,以放入我的 Course 模型中。

谢谢。

【问题讨论】:

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


    【解决方案1】:

    如此处所示(使用连接模型创建范围):problem: activerecord (rails3), chaining scopes with includes

    这里(多列排序):Ruby on Rails: how do I sort with two columns using ActiveRecord?

    最后在这里(按关联模型排序):Rails 3. sort by associated model

    你可以这样实现:

    scope :complex_sorting, lambda {
        joins(:questions)
        .order('questions_count DESC, question.answers_count DESC, created_at DESC')
    }
    

    【讨论】:

    • 如上所示键入代码会导致“尝试在没有块的情况下创建 Proc 对象”错误。在看到提出类似问题后,我将代码重新格式化为scope :by_most_popular, lambda { |course| joins(:question).order('questions_count DESC, question.answers_count DESC, created_at DESC') }。但是,现在 Ruby 抱怨“参数数量错误(0 代表 1)”
    • 更新了我的答案,将“do...end”替换为大括号。您对“错误数量的参数错误(0 代表 1)”有更高的精度吗?
    • 我做了更多的挖掘以找出“错误参数”错误背后的原因。我重写了一个更简单的范围方法来测试连接是否正常工作 (scope :by_answer_count, -&gt; { joins(:question).order('question.answers_count DESC') }),我收到错误“找不到名为‘问题’的关联;也许你拼错了?”。鉴于模型相关的方式,我不明白为什么它找不到 question 模型。我认为这可能会抛弃更复杂的排序方法。
    • 考虑到has_many 关系,可能是:questions 而不是:question
    • 我的错误,我认为您不需要传递参数(正如您的第一个错误所说)只需删除|course|。它用于您将参数传递给您的范围......对此感到抱歉
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-14
    • 1970-01-01
    相关资源
    最近更新 更多