Post

ActiveRecordの結果を配列に変換

解決

to_a を使用する。

SomeModel.where(id: [0, 1]).to_a

ruby-on-rails – Rails:activerecordの関係を配列に変換する正しい方法は? - コードログ

起因

プログラム

results = self. select( 'inquiry.id as inquiry_id', 'model3.id as model3_id' ). joins(model1: [:model2, { model3: :model4 }]). where(model1: { id: [0, 1] }). distinct # 上記のActiveRecodeに含めればいいが、同テーブルがinner joinとleft joinに混在しエラーとなる。 # その為、プログラムでleft joinを請け負っている。 results2 = Model3.eager_load(:model5).where(id: results.map{ |m| m[:model3_id] }).all results.each do |result| inquiry_myobject_relations.each.with_index do |inquiry_myobject_relation, i| if result[:model3_id] == results2[:id] result[:model5_id] = results2.model5.id inquiry_myobject_relations.delete_at(i) # 一度合致したら以降はしないため break end end end

エラー

NoMethodError: undefined method `delete_at' for #<Model3::ActiveRecord_Relation:0x000055a70a55b6b0> Did you mean? delete_all delete from /usr/local/bundle/gems/activerecord-5.0.1/lib/active_record/relation/delegation.rb:123:in `method_missing'

allって配列とばかり思っていたら、正体は ActiveRecord::Relation でした。

また、can't modify frozen Array とdelete_atのような破壊はできない。
This post is licensed under CC BY 4.0 by the author.