Question about hashes in views that model a table?

if i have a table called cars with columns called year and type, and i
create a model and do this

@mycars = Cars.find(:all)

in my view i have something like this

for cars in @mycars
do something like print out cars.type

i know that @mycars in a hash where each key is a column name paired
with its corresponding value right?

without the for loop, how can i access the 2nd record directly?
@mycars[0].type = ?

how does the variables in the view know that cars relate to the Cars
table?

is that for loop the same as something like this in c++

for (int i = 0; i < mycars.total; i++)

ive also wondered this.

baker1 wrote:

i know that @mycars in a hash where each key is a column name paired
with its corresponding value right?

@mycars will be an array of Car objects, each containing an attribute
hash with column name keys.

without the for loop, how can i access the 2nd record directly?
@mycars[0].type = ?

@mycars[1].type = ?, though you probably will not know what car
this is unless you use an :order option in your find that is
some sort of consecutive sequence number.


We develop, watch us RoR, in numbers too big to ignore.

koloa wrote:

hi mark, thanks for the response

so it is an array of carobjects, where each car object is a hash with
each key being a column name in a table.

A Car object is a proper Ruby object that contains many things.
One of these things is an @attributes instance variable (also
accessible through the “attributes” method), which is a hash with
column name keys. But you usually don’t access this directly.
Rather you use either the attribute access square brackets operator,
or the automatic column-named attribute methods. That is, the
following are equivalent ways to access the “make” column value
of the first Car object found:

     @mycars[0].attributes['make']
     @mycars[0]['make']
     @mycars[0][:make]
     @mycars[0].make


We develop, watch us RoR, in numbers too big to ignore.

hi mark, thanks for the response

so it is an array of carobjects, where each car object is a hash with
each key being a column name in a table.

Mark Reginald J. wrote:

baker1 wrote:

i know that @mycars in a hash where each key is a column name paired
with its corresponding value right?

@mycars will be an array of Car objects, each containing an attribute
hash with column name keys.

without the for loop, how can i access the 2nd record directly?
@mycars[0].type = ?

@mycars[1].type = ?, though you probably will not know what car
this is unless you use an :order option in your find that is
some sort of consecutive sequence number.


We develop, watch us RoR, in numbers too big to ignore.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs