0

I'm trying to run a simple fetch using ActiveRecord and I'm confused by the result. This is the code I'm trying to run

c = Child.where("name LIKE ?", "%John D%")

I have a Child model and a corresponding table in my database. There is a record for "John Doe" in the database that outputs as being found in the rails console. However, when I execute

c.name

It outputs

=> "Child"

instead of

=> "John Doe"

If I run

c = Child.find_by_name("John Doe")

everything works fine. I'm sure there is an obvious solution here, but I just can't seem to figure it out.

1 Answer 1

3

The where returns an ActiveRecord Relation. If you do a c.class that will give you ActiveRecord::Relation::ActiveRecord_Relation_Child. To get an actual object you can just do:

c = Child.where("name LIKE ?", "%John D%").first

Note that will be nil if there are no results for the query.

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

2 Comments

This works. You can also use c = Child.where("name LIKE ?", "%John D%").all to get an Array of all matching results
Yup! There are lots of things you can do with the results :).

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.