问题
Upgraded app to Rails 5 using the index method. The issue is that it is not incrementing to the next ActiveRecord collection record. The below code below use to work in Rails 4.0. Tried with index_by.
def next_question
index = campaign.quiz_questions.index self
campaign.quiz_questions[index + 1]
end
Debugger
(byebug) campaign.quiz_questions.index
*** NoMethodError Exception: undefined method `index' for #<QuizQuestion::ActiveRecord_Associations_CollectionProxy:0x007f80012d71b0>
Did you mean? index_by
Using index_by
(byebug) index = campaign.quiz_questions.index_by
#<Enumerator: #<ActiveRecord::Associations::CollectionProxy [#<QuizQuestion id: 113, campaign_id: 492, message: "Where did Hullabalooza's freak show manager send H...", created_at: "2016-07-20 20:50:32", updated_at: "2016-07-20 20:50:32">]>:index_by>
Index + 1
(byebug) index + 1
*** NoMethodError Exception: undefined method `+' for #<Enumerator:0x007fc4db445960>
nil
回答1:
changed it to find_index
method. Now it's working
def next_question
index = campaign.quiz_questions.find_index self
campaign.quiz_questions[index + 1]
end
来源:https://stackoverflow.com/questions/38490650/rails-5-activerecord-collection-index-by