Return the name instead of the ID in a Rails relationship

Asked

Viewed 124 times

0

I have two related tables in Rails, pessoa and cidade.

On the table pessoa have the field cidade_id.

How to do, for example, p = Pessoa.find(1) and in place of p.cidade_id already return the name of the city without I need to do p.cidade.nome?

1 answer

3

You can search by city name in the same search to find the person, using the includes which will not do additional query. It would be something like:

Person.includes(:city).where(id: 1).pluck(:name, 'cities.name')

as long as there is in your code this association mapped in the model.

Using the includes, even if in your loop you need to call p.cidade.nome, no further wishes will be made.

TIP: It is worth a search in preload x includes x joins so that you can always choose which method to apply.

  • thanks very much worked out, I’m using as api so just use render :json => @people.to_json(:include => :city) in the controller that returns 1 json {people: {id: 1, name: "test"...} city:{id:1 name: ...} }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.