Rails:获取记录的位置?

假设我有一个Questions模型,我将所有答案都提取到一个特定问题。

我可以轻松地执行each_with_index并找出答案的索引或“位置”(与该特定问题的其他答案相关)。

但是,说我想得到一个具体的答案……我怎么还能弄清楚答案的索引与特定问题相关的所有其他答案的关系。

示例Answer数据:

 ID text question_id 23 awesome 3 27 boooyah 3 38 snap 3 

如果我做了Answer.find(27)我怎么能弄清楚该记录是第二项(假设我按ID排序……虽然我可以在任何领域订购)。

 class Answer < ActiveRecord::Base belongs_to :question def position(column = 'id', order = 'ASC') order_by = "#{column} #{order}" arrow = order.capitalize == "ASC" ? "<=" : ">=" question.answers.where("#{column} #{arrow} (?)", self.send(column)).order(order_by).count end end Answer.find(27).position Answer.find(27).position("updated_at") Answer.find(27).position("updated_at", "DESC") 

这样的东西应该有用,它没有经过测试,但你可以看到这个概念。

 class Answer < ActiveRecord::Base belongs_to :question def placement(ordering_by => 'id ASC') question.answers.order(ordering_by).index(self) end end