-2

Straight forward here:

                 <% @yyy = CityRace.where(city_race_id2: "3") %> 
                 <% @xxx =  @yyy.name %> 

The @yyy is returning the proper record using the ID I have passed into it, but I'm trying to get the objects name. For some reason .name isn't working. Any idea what I'm going wrong here?

How do I find a record's name where id = a certain id?

Wes Creations
  • 337
  • 2
  • 10
  • 1
    If CityRace has a name field, and the item with that ID has a name, that should be just fine. What do you see if you just print `@yyy`? – Balastrong May 24 '20 at 17:30
  • @Balastrong undefined method `name' for # – Wes Creations May 24 '20 at 17:32
  • 1
    And if you print only `@yyy`? not `@yyy.name` – Balastrong May 24 '20 at 17:33
  • Welcome to SO. Please see "[ask]", "[Stack Overflow question checklist](https://meta.stackoverflow.com/questions/260648)" and "[MCVE](https://stackoverflow.com/help/minimal-reproducible-example)" and all their linked pages. You're asking us to help debug code but didn't provide code that duplicates the problem. – the Tin Man May 24 '20 at 17:36
  • _"The @yyy is returning the proper record"_ – no, it returns an instance of `ActiveRecord::Relation` which is a proxy to all records (plural) with a `city_race_id2` of `"3"`. – Stefan May 25 '20 at 08:44

2 Answers2

3

where returns an ActiveRecord_Relationship, meaning an object containing CityRace objects for every row in the database with city_race_id2 equals to 3, no matter if there's only one, the result is an ActiveRecord_Relationship object, and that doesn't respond to name.

If you need the name of a particular object from that result, you can access to the specific element by its index and invoke name on it, e.g:

CityRace.where(city_race_id2: "3").first.name

Or to retrieve the name from every object:

CityRace.where(city_race_id2: "3").pluck(:name)

this one returns an array of strings, so, you must iterate over them to print them all or get a specific one.

In the other hand if you need a single row from the query, use find_by:

CityRace.find_by(city_race_id2: "3").name
Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
2

.where returns an ActiveRecord::Relation which behaves like an array. You can think of it like a special kind of array that allows you to chain on more active record queries on it. When you call certain methods like each or to_a it evaluates the query into an actual array.

In any case, what you are looking for here is not something array-like. You want @yyy to refer to a single record.

Simple fix, just use find_by instead of where. Also take a look at https://api.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-find and find vs find_by vs where

max pleaner
  • 26,189
  • 9
  • 66
  • 118