【问题标题】:Difficulty sorting entries based on attributes of related models基于相关模型属性的条目排序困难
【发布时间】:2013-01-31 19:59:04
【问题描述】:

我无法实现一项功能,该功能允许用户查看根据属于它的各种属性(即问题是否已回答?每个问题回答多少等)排序或过滤的问题(我的模型),这将基于Question模型的属性,或者相关模型的属性到Question

我有以下型号:

class Question < ActiveRecord::Base    
  belongs_to :course
  belongs_to :user
  has_many :answers, inverse_of: :question
  belongs_to :accepted_answer, class_name: :answer, foreign_key: :accepted_answer_id

  default_scope order: 'questions.created_at DESC'
end

class Answer < ActiveRecord::Base
  belongs_to :user
  belongs_to :question, inverse_of: :answers
  has_many :a_votes

  default_scope order: 'answers.created_at DESC'

  def accepted?
    return false if new_record? 
    question.try( :accepted_answer_id ) == id
    # an alternative is to use question.try( :accepted_answer ) == self
  end
end

我要添加的是控制器中的排序或过滤器,例如“仅查看已回答的问题”,其中仅包含question.accepted_answer == true 的问题。实现这一目标的最佳方法是什么?是否有任何关于 ActiveRecord 过滤/排序的指南可供我参考以供将来参考?

谢谢!!

附录

我将问题显示为呈现_question.html.erb 并通过问题父级Groupshow 函数调用它(因此,每个Grouphas_many 问题)

class CoursesController < ApplicationController
  def show
    @course = Course.find(params[:id])
    # @questions = @course.questions.all this is the default selection
    @questions = @course.questions.by_answer_count #maybe Im not calling the scope correctly (and sorry if I am making a noob mistake..)
  end
  #There are other methods not shown
end

【问题讨论】:

  • 我不知道这是否真的是你要找的东西 - 但调查一下:github.com/ernie/ransack - Ransack Gem 不会受伤
  • @MartinLang 这看起来真的很酷,我可能会同意我无法让我自己的排序/过滤逻辑工作。感谢分享这个很酷的宝石。

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


【解决方案1】:

我通过使用连接和分组在父模型上定义范围来实现这种功能。

例如,此范围将按答案数量(降序)对问题进行排序。

class Question
  scope :by_answer_count, -> {
    joins(:answers).reorder("count(answers.id) DESC").group(:id)
  }
end

希望对你有帮助。

【讨论】:

  • 感谢 Shane 分享您的答案。当代码执行时,不幸的是显示的顺序根本没有改变。我什至在取消注释我的default_scope 设置后尝试了它以显示最后创建的内容。我将更多代码粘贴到我的问题正文中以防万一。
  • 是的,我没有意识到Question 上有一个默认范围。此方法应改用reorder。我已经相应地对其进行了编辑。让我知道这是否有效。
  • 感谢您的编辑.. 不幸的是仍然无法正常工作。我想确保我在控制器中调用它的方式是正确的:@questions = @course.questions.by_answer_count。在我看来,然后我打电话给render @questions
  • 这对我来说是正确的。尝试打开控制台rails console并执行Course.find(id).questions.by_answer_count,看看order子句是否被应用于SQL语句。
  • 很好的调试技巧。在 Rails 控制台中进行查询时,我收到错误“未定义的方法 `by_answer_count'”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
  • 2012-06-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多