如何使用arel / relational algebra和has_many:through获取不同的值

时间:2011-02-26 05:13:02

标签: ruby-on-rails distinct arel relational-algebra

当我尝试显示一个人所在的所有电影,并且他们在电影中有超过1个角色(导演,作家,演员)时,我会为该电影获得多行。如果我添加.select('DISTINCT id')或电影。*来尝试消除重复,我会收到以下错误:

  

Mysql2 ::错误:您的SQL语法中有错误;检查与您的MySQL服务器版本对应的手册,以便在{DISTINCT id movies INNER JOIN movie_people附近movies附近使用正确的语法.id = movie_peop' at line 1: SELECT movies {{ 1}}电影.*, DISTINCT id FROM movie_people INNER JOIN电影ON movie_people .id = movie_people`.person_id = 601619))ORDER BY title LIMIT 18 OFFSET 0

我不知道如何正确编码arel请求。请帮忙。
谢谢。

应用程序/控制器

.movie_id WHERE ((

应用程序/模型

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  

db / schema.rb

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  

movies / show.html.erb

  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  

标题:华氏9/11
年份:2004年 导演:Michael Moore 作家:Michael Moore
演员:迈克尔摩尔乔治W.布什

people / 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 %>  

姓名:Michael Moore
华氏9/11(2004)
华氏9/11(2004)
华氏9/11(2004)

3 个答案:

答案 0 :(得分:3)

在Arel中,uniq生成相应的select distinct SQL。我不确定如何将Arel添加到has_many关联中,但在常规(控制器)代码中它将类似于

@person.movies.uniq

请参阅http://apidock.com/rails/ActiveRecord/QueryMethods/uniqRails Arel selecting distinct columns

答案 1 :(得分:2)

这可能是Rails的一个错误。

与此同时,您可以排除选择之前选择选择distinct,如下所示:

@person.movies.except(:select).select('DISTINCT id')

答案 2 :(得分:1)

这解决了我的问题 - rails - using :select(distinct) with :has_many :through association produces invalid SQL

has_many :movies, :through => :movie_people, :select => 'distinct movies.*'