craftdeer
craftdeer

Reputation: 1025

How to show values of referenced tables in rails?

I am very new to rails and have made a basic app with two tables but I have not figured out how to show the value of the referenced table instead of the id. My two tables are Genres and Songs and look like this.

id | trackgenre  |         created_at         |         updated_at         
----+-------------+----------------------------+-------------------------

  1 | Classic | 2017-06-13 02:37:07.041974 | 2017-06-13 02:37:07.041974

  2 | Rock     | 2017-06-13 02:37:07.060634 | 2017-06-13 02:37:07.060634

  3 | Hip-Hop   | 2017-06-13 02:37:07.064877 | 2017-06-13 02:37:07.064877

  4 | Alternative     | 2017-06-13 02:37:07.067473 | 2017-06-13 02:37:07.067473





  id | songtitle  |         artist        |         genre_id         
----+-------------+----------------------------+---------------------------

  1 | Loser         | Beck                  | 4

  2 | Jailhouse rock | Elvis Presley        | 2

  3 | My Way        | Frank Sinatra         | 2

My song.rb looks like this

class Song < ApplicationRecord
  belongs_to :genre
end

and genre.rb is

class Genre < ApplicationRecord
  has_many :songs
end

Now when I am fetching data from the front end, I see the genre_id instead of the value. For example, if i fetch the second item from my Songs table, I get Jailhouse rock, Elvis Presley, 2. What would I have to do to get the value of genre_id that is "Rock" to show up on the front end instead of this number 2?

Upvotes: 0

Views: 49

Answers (2)

moyinho20
moyinho20

Reputation: 624

If you are fetching the second item from Songs simply by

Song.second

This would give you genre_id which is in the Songs table. If you want name of the genre or in this case `trackgenre, you'll have to join the tables:

Song.joins(:genre).select("songs.*", "genres.trackgenre").second

This would give you all attributes of Song and Genre Name, which means genre_id and trackgenre. If do not want genre_id and just trackgenre, you will have to select attributes of the song.

Song.joins(:genre).select("songs.id", "songs.songtitle", "songs.artist", "genres.trackgenre").second

Upvotes: 0

Pavan
Pavan

Reputation: 33542

I have not figured out how to show the value of the referenced table instead of the id

You just need to do

<%= @song.genre.trackgenre %>

Where @song is an instance of Song

Upvotes: 2

Related Questions