1

I have a model Image:

class Image < ActiveRecord::Base
  attr_accessible :date, :description, :name, :quality, :size
end

I now have an instance variable with a bunch of images:

@images = Image.where("id<30")

I want to create a @keywords variable with all the names of the images. In the Rails console I can do:

for i in [email protected]
  puts @image[i].name
end

and I get a list of all the name of the images.

How can I define the @keywords variable in my images_controller in order to store this list in an array?

@keywords = ...?

The output should be a list, preferrably comma seperated, with the image names:

"Blue ocean, Green leafs, Sunset in New York"

1 Answer 1

4
@keywords = @images.collect{|i| i.name}.join(",")

This will get an array of all the names and join them into a comma-separated string.

Sign up to request clarification or add additional context in comments.

4 Comments

shorter: @images.map(&:name).join(',') :-)
shorter: @images.map(&:name) * ',' if we're playing that game.
Is this just "nice" to change it to the short version or is this also a performance issue, means the query will take less time?
This is mostly syntactic sugar - according to the docs, #map is an alias of collect and #* with a string is the same as join. Whether or not the &:name syntax is any faster than the block I provided, I'm not sure.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.