Rails: Get posting?

Let's say I have a Questions and Answer model, and I will answer all the answers to a specific question.

I can easily do each_with_index to and find out what the index or β€œplacement” of the answer is (relative to other answers to this particular question).

But, say, I want to get a specific answer ... how can I guess what is the index of this answer in relation to all other answers related to a particular question.

Example Answer data:

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

If I made Answer.find(27) , how can I determine that the record is the second element (if I order by ID ... although I could order any field).

+6
object arrays ruby-on-rails order
source share
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") 
+6
source share

Something like this should work, it has not been 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 
+1
source share

All Articles