Position of object in database

岁酱吖の 提交于 2019-12-25 00:42:21

问题


I have got model Team and I've got (i.e.) team = Team.first :offset => 20. Now I need to get number of position of my team in db table.

I can do it in ruby:

Team.all.index team #=> 20

But I am sure that I can write it on SQL and it will be less expensive for me with big tables.


回答1:


Assuming the order is made by ID desc:

class Team < ActiveRecord::Base
  def position
    self.class.count(:conditions => ['id <= ?', self.id]) 
  end
end



回答2:


I'm not sure I'm following along, but will position value be used a lot it might be worth making sure it is set on save. Will a team change position over time or is it static?

I don't think the position of a record in the database is one of the things a database really cares for, that kind of data should be up to you to set.

Depending on the database you may be able to use the LIMIT clause, but you can't use it to find the position of a certain row. Just to select rows number 20 to 21 for example, but it'll differ depending on sorting order.

SELECT * FROM teams LIMIT 20,21

I think setting a position attribute on your model or having a join model is the way to go.



来源:https://stackoverflow.com/questions/2763801/position-of-object-in-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!