Home > Software design >  How to select distinct name from associated columns in rails
How to select distinct name from associated columns in rails

Time:01-03

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

CodePudding user response:

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.

CodePudding user response:

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
  • Related