I have a table named "Projects" which has a column "name". I want to get
a string array to represent all the name values. In the controller, I
can use this code "@projects = Project.find(:all)" to get all the
projects but how to convert it to the string array?
all work.
I think the first last and all refers to rows. I want to select columns.
If I'm not wrong, relational algebra doesn't identify a sequence between the elements of a row, i.e., I don't think it gives you the ability to select a column specifically. That said, you could probe for the schema and get the elements using that - something like how the dynamic scaffold used to work in earlier Rails.
A more efficient way is to do this is:
@project_names = Project.all(:select => 'name').map(&:name)
While you've made a database optimisation there, you've also used the
shorthand notation for the map function. I read somewhere that map
(&:name) is quite a bit less efficient than map{ |p| p.name }
unfortunately I can't find the article that convinced me in the first
place... I can only find this blog with the issue mentioned in the
comments: