When I try to display all movies that a person is in, and they have more than 1 role (director,writer,actor) in a movie, I get multiple lines for that movie. If I add .select('DISTINCT id') or movies.* to try and eliminate the dups I get the following error:
Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DISTINCT id FROM
movies
INNER JOINmovie_people
ONmovies
.id =movie_peop' at line 1: SELECT
movies.*, DISTINCT id FROM
moviesINNER JOIN
movie_peopleON
movies.id =
movie_people.movie_id WHERE ((
movie_people`.person_id = 601619)) ORDER BY title LIMIT 18 OFFSET 0
I don't know how to code the arel request correctly. Please help.
Thank you.
app/controllers
class PeopleController < ApplicationController def show @person = Person.find(params[:id]) @movies = @person.movies.select('DISTINCT id'). paginate :per_page => 18, :page => params[:page], :order => sort_order(params[:sort]) end
app/models
class Person < ActiveRecord::Base has_many :movie_people has_many :movies, :through => :movie_people end class MoviePerson < ActiveRecord::Base belongs_to :movie belongs_to :person end class Movie < ActiveRecord::Base has_many :movie_people has_many :people, :through => :movie_people end
db/schema.rb
create_table "people", :force => true do |t| t.string "name" end create_table "movie_people", :force => true do |t| t.integer "movie_id" t.integer "person_id" t.integer "role" end create_table "movies", :force => true do |t| t.string "title" t.string "year" end
movies/show.html.erb
Title:<%= @movie.title %><br> Year:<%= @movie.year %><br> <% @movie.movie_people.group_by(&:role).each do |r, a| %> <%= %w(Director: Writer: Cast:)[r] %> <% a.each do |c| %> <%= link_to c.person.name, :controller => 'people', :action => 'show', :id => c.person.id %> <% end %><br> <% end %>
Title: Fahrenheit 9/11
Year: 2004
Director: Michael Moore
Writer: Michael Moore
Cast: Michael Moore George W. Bush
people/show.html.erb
Name:<%= @person.name %> <% @movies.each do |movie| %> <br><%= link_to movie.title, movie %> (<%= movie.year %>) <% end %>
Name: Michael Moore
Fahrenheit 9/11 (2004)
Fahrenheit 9/11 (2004)
Fahrenheit 9/11 (2004)