0

I am working on a netflix clone project in ruby on rails and I need to get distinct genre name from an associated column in rails. That means, from the first table I have the 'genre_id' and from the second I have the 'name' of the genre. So how can I get this 'name'?

Movie Table

Title | Genre
xxxx  |  1
aaaa  |  1
bbbb  |  1
cccc  |  1
zzzz  |  2
dddd  |  2
eeee  |  2
gggg  |  2

Genre Table

 id  | name
  1  | Action
  2  | Romance

In Model

@action = Movie.where(genre_id: 1)

Try

<%= @action.select(:genre_id).distinct %>

Result

#<Movie::ActiveRecord_Relation:0x00007fb908040470>

Expected

Action

PS: These return error

<% @action.first.genre_id.name %>
<% @action.select(:genre_id).first.name %>
<% @action..select(:genre_id).distinct.as_json %> --> returns [{"genre_id"=>1, "id"=>nil}]
<% @action.first.genre_id %> --> returns 1
Kelson Batista
  • 406
  • 4
  • 25
  • Could you provide code for your Movie and Genre models ? – Risalat Zaman Dec 31 '22 at 20:33
  • `select` should give you just the IDs as that's *all* you're asking for. Maybe you want `@action.select(:name).distinct` or `Movie.includes(:genre).select('genres.name').distinct`. – tadman Dec 31 '22 at 21:18

2 Answers2

0

Because I can not comment yet, I will answer. It's an old question, for Rails 5+ you should use the following:

@action.distinct.pluck(:genre_id)

It will return an array of unique genre_id's.

metacorn
  • 52
  • 3
0

I'm assuming you only have the title from the movie table or genre_id (according to the example). You would have to look up the genre table to get the 'Action' string returned.

action = Genre.where(id: 1)

If you have to make a link from the movie to genre table, that will go something like this:

movies = Movie.includes(:genre)
movies.first.genre.name # this will return the action string
# or, pick a specific movie and look up its genre
movies.where(:title => 'xyz').first.genre.name
Sindhu Shree
  • 158
  • 2
  • 11