ruby on rails - ActiveRecord relationships and the object model -
hi ran when trying following:
posts = user.first.posts posts.find {|p| "p.id" == 123} => activerecord::recordnotfound: couldn't find post without id that trying call activerecord find. it's expecting:
posts.find(123) but dont want query db again. need do:
posts.to_a.find {|p| "p.id" == 123} i though dealing array, according posts.class. why have call to_a on it?
posts.class => array posts.superclass => activerecord::base why can call superclass on posts if it's (presumably) instance of array , why return activerecord::base?
also:
posts.ancestors.include? activerecord::base => false why false if activerecord::base superclass of posts array?
one more. if do:
posts.instance_methods(false) it returns instance methods of class of relationship, i.e. post. seems weird since posts array. if create "regular" array:
a = [1, 2] a.instance_methods(false) => nomethoderror: undefined method `instance_methods' [1, 2]:array so array returned via activerecord relationship query sort of array not...it seems inherits activerecord, doesn't...or something. when thought getting solid grasp of ruby object model :) maybe under-the-hood @ activerecord help. i'm not sure, that's why i'm asking guess.
this curiosity thing. help/guidance appreciated
you want:
posts.detect {|p| p.id == 123} find alias of detect, shadowed find method on activerecord collection proxy posts.
Comments
Post a Comment