【发布时间】: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 并通过问题父级Group 的show 函数调用它(因此,每个Group 将has_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