扶手:获取记录的位置? [英] Rails: Get placement of records?

查看:99
本文介绍了扶手:获取记录的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个问题模型和我拉所有的答案,以一个具体的问题。

我可以轻松地做一个 each_with_index 来,并找出一个答案的索引或安置是什么(相对于其他的答案到具体的问题)。

不过,说我希望得到一个明确的答案......我怎么可能还找出这个问题的答案的指数相对于与特定问题相关的所有其他的答案。

示例数据:

  ID文本question_id
23真棒3
27 boooyah 3
38单元3

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


解决方案

 类应答和LT; ActiveRecord的::基地
  belongs_to的:问题  高清位置(列='ID',为了='ASC')
    ORDER_BY =#{列}#{}秩序
    箭头= order.capitalize ==ASC? &所述=:=>中
    question.answers.where(#{列}#{}箭头(?),self.send(列))。为了(ORDER_BY).Count之间
  结束
结束Answer.find(27).POSITION
Answer.find(27).POSITION(的updated_at)
Answer.find(27).POSITION(的updated_at,DESC)

Say I've got a Questions and Answer model and I pull all the answers to a specific question.

I can easily do an each_with_index to and figure out what the index or "placement" of an answer is (in relation to the other answers to that specific question).

But, say I want to get a specific answer...how could I still figure out what the index of that answer is in relation to all the other answers associated with a specific question.

Example Answer data:

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

If I did Answer.find(27) how can I figure out that record is the second item (assuming I'm ordering by ID...though I could order by any field).

解决方案

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")

这篇关于扶手:获取记录的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆