当我尝试显示一个人参与的所有电影,并且他们在一部电影中扮演多个角色(导演、作家、演员)时,我会得到该电影的多行。如果我添加 .select('DISTINCT id') 或 movies.* 来尝试消除重复,我会收到以下错误:
Mysql2::Error: 你的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册以获取正确的语法,以便在 '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附近使用
我不知道如何正确编码 arel 请求。请帮忙。
谢谢你。
应用程序/控制器
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
应用程序/模型
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
数据库/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
电影/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 %>
标题:华氏 9/11
年:2004 年
导演:迈克尔·摩尔
编剧:迈克尔·摩尔
演员:迈克尔·摩尔乔治·W·布什
人/show.html.erb
Name:<%= @person.name %>
<% @movies.each do |movie| %>
<br><%= link_to movie.title, movie %> (<%= movie.year %>)
<% end %>
名称: Michael Moore
华氏 9/11 (2004)
华氏 9/11 (2004)
华氏 9/11 (2004)