I want to add every nested resource's parameter to an array. The main resource is stream
and the nested resources are videos
@stream = Stream.friendly.find(params[:id])
@firstvideo = @stream.videos.first
I want to store
array[] = [firstvideo.video_id , secondvideo.video_id , thirdvideo.video_id .....]
video_id
is a parameter for each video. How can I create a method that will accomplish this?
Use pluck
to get the video IDs from an association:
ids = Stream.friendly.find(params[:id]).videos.pluck(:id)
This will generate a select video_id from videos where ...
query and only instantiate the array of returned IDs, side-stepping the expensive process of building Video
objects for each record.
If you have an already instantiated list of Video
objects, use map
to produce an array of IDs:
ids = @videos.map(&:id) # equivalent to .map { |v| v.id }