Rails - Can't get only a few of the attributes for all objects in an array? -


i have service puts array of answer objects, each containing string answer text, boolean indicating whether it's correct answer or not , it's id. code far:

@quiz.questions[current_question_index].answers 

it works. take array of answer objects , send on actioncable channel displayed buttons - works.

but i'm thinking better not send entire answer objects (including information of answers correct), id , title tried change code according this post:

@quiz.questions[current_question_index].answers.pluck(:id, :title) 

this not work me - buttons read "undefined". tried way according this post:

@quiz.questions[current_question_index].answers.attributes.slice('id', 'title') 

now buttons don't displayed anymore...

what want array of objects contain attributes 'id' , 'title' retrieved answers.

can give me pointers fix this? i'm rails beginner , appreciate help.

as said answers array, , pluck method not available on array (it's ar magic)

and fix, buttons stopped displaying because before had array of answer objects, , have array of hashes keys: id , title.

you should check inspector in browser (f11 in chrome) see kind of javascript errors have , fix accordingly.

sending hashes instead of full objects idea, need change way use them on receiving end.

edit:

regarding attributes need this

@quiz.questions[current_question_index].   answers.map{|answer| answer.attributes.slice('id', 'title') 

it have effect you'd expect.

regarding "rails magic". meant this: rails don't call query until last moment, instead have object answer::activerecord_relation allows call active record methods on (pluck among them).

in example build array of answers , can't call pluck on array - it's not defined.

i hope it's more clear now.


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -