Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Get placement of records?

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

like image 477
Shpigford Avatar asked Apr 06 '11 17:04

Shpigford


2 Answers

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")
like image 156
fl00r Avatar answered Oct 29 '22 14:10

fl00r


Something like this should work, it's not tested but you can see the concept.

class Answer < ActiveRecord::Base

  belongs_to :question

  def placement(ordering_by => 'id ASC')
    question.answers.order(ordering_by).index(self)
  end

end
like image 44
ctcherry Avatar answered Oct 29 '22 14:10

ctcherry