Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails ActiveRecord find in console

When I'm in the Rails 3.2 console, I can do this just fine:

p = Person.last
p.last_name

and it prints the last name.

But when I try to find it by the id, it's able to locate the single record and store it in my variable p, but I can't print the last_name column. For example:

p = Person.where(id: 34).limit(1)

printing p here shows all the columns but p.last_name says this

NoMethodError: undefined method `last_name' for
#<ActiveRecord::Relation:0x000000055f8840>

any help would be appreciated.

like image 406
user740970 Avatar asked May 19 '12 01:05

user740970


People also ask

What is ActiveRecord in Ruby on Rails?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.

How do I open rails console?

Go to your browser and open http://localhost:3000, you will see a basic Rails app running. You can also use the alias "s" to start the server: bin/rails s . The server can be run on a different port using the -p option. The default development environment can be changed using -e .

What is ActiveRecord base?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.


2 Answers

A where query will return an ActiveRecord::Relation, which sort of acts like an array, even if you limit the number of returned records.

If you instead change your query to:

p = Person.where(id: 34).first

it will work as you want, and arel knows to automatically limit the query to a single result, so you don't have to explicitly specify limit(1).

You could also change to either

p = Person.find(34) # Throws an ActiveRecord::RecordNotFound exception if Person with id 34 does not exist

or

p = Person.find_by_id(34) # Returns nil if Person with id 34 does not exist. Does *not* throw an exception.

and it will return a single record as expected.

EDIT: A where query returns an ActiveRecord::Relation, as @mu is too short mentioned in comments.

like image 106
x1a4 Avatar answered Sep 23 '22 10:09

x1a4


This returns a collection of active record objects:

p = Person.where(id: 34).limit(1)

But there's only one with id = 34, so it's a collection of 1.

The way to do this is:

p = Person.where(id: 34).limit(1).first

or, better:

p = Person.where(id: 34).first

or, even better:

p = Person.find(34)
like image 40
Kevin Bedell Avatar answered Sep 19 '22 10:09

Kevin Bedell