bcoughlan
bcoughlan

Reputation: 26617

Ruby/Rails 3: Turning a set of object attributes into an array

@video = Video.find(params[:id])

@lengths = @video.each do |i|
  @length = i.length * 60
end

Firstly, I presumed @video would have an each, but instead got this error:

undefined method `each' for #<Video:0x4738428>

Secondly, is there any Ruby one-liner magic that could substitute for the last 3 lines?

Upvotes: 0

Views: 427

Answers (2)

fengolly
fengolly

Reputation: 503

Pizzicato answered your question just fine, but here's my two cents:

If you would like to know the class of an object, you can do:

p Video.find(params[:id]).class

Upvotes: 1

Pizzicato
Pizzicato

Reputation: 1621

@video is not an array in this case, it is an object because you asked the Video model to return only one video, the one with the id given in the params array.

In case you want to retrieve all videos from the database, do this:

@video = Video.all

Now @video will be an array of video objects.

Upvotes: 4

Related Questions