0

I'm using Rails and in a controller, I have a database called log_cons and it has an entry all filled in whereby the first column is "id" and the value is "1"

@log_cons = LogCon.all
puts @log_cons[1].id

This outputs to the browser:

Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id

and prints an empty line in the terminal.

What could be some potential reasons for this?

2 Answers 2

1

LogCon.find() will return an ActiveRecord object, not an array.

Thus you can just get the id like so:

@log_cons = LogCon.all
puts @log_cons[0].id

or

puts @log_cons.first.id
Sign up to request clarification or add additional context in comments.

4 Comments

Oh, I am trying to get an array of all the records. How would I do that, and print the id for each?
LogCon.all will return all the objects, then you can just loop through each of the elements like so LogCon.all.each { |o| puts o.id }
You can also do @log_cons.first.id
I agree with Luís, using first is much more elegant.
1

If you want all records, do

@log_cons = LogCon.all

and then access the first one doing

puts @log_cons[0].id

2 Comments

@log_cons[0].id is the first result.
If you are searching for the first object inside that array, your index has to be zero, not one - i.e. puts @log_cons[0].id instead of puts @log_cons[1].id

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.