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")
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With