Rails 5: ActiveRecord collection index_by

…衆ロ難τιáo~ 提交于 2020-01-23 12:28:06

问题


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

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