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

当我试图显示一个人所在的所有电影,并且他们在电影中有超过1个角色(导演,作家,演员)时,我会为该电影获得多行。如果我添加.select('DISTINCT id')或电影。*来尝试消除重复,我会收到以下错误:   Mysql2 ::错误:您的SQL语法有错误;查看与您的MySQL服务器版本对应的手册,以便在'DISTINCT idFROM
movies
INNERJOIN附近使用正确的语法
movie_people
ON
movies
.id=
movie_peop' at line 1: SELECT
movies
.*, DISTINCT id FROM
movies
INNER JOIN
movie_people
ON
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  
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  
电影/ 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年 导演:Michael Moore 作家:迈克尔摩尔 演员:迈克尔摩尔乔治W.布什 人/ show.html.erb
Name:<%= @person.name %>
<% @movies.each do |movie| %>  
<br><%= link_to movie.title, movie %> (<%= movie.year %>)  
<% end %>  
姓名:迈克尔摩尔 华氏9/11(2004) 华氏9/11(2004) 华氏9/11(2004)     
已邀请:
在Arel中,
uniq
生成适当的
select distinct
SQL。我不确定如何将Arel添加到has_many关联中,但是在常规(控制器)代码中它会像
@person.movies.uniq
请参阅http://apidock.com/rails/ActiveRecord/QueryMethods/uniq和Rails Arel选择不同的列     
这可能是Rails的一个错误。 在此期间,您可以在select之前排除select,如下所示:
@person.movies.except(:select).select('DISTINCT id')
    
这解决了我的问题 - rails - 使用:select(distinct)with:has_many:通过关联产生无效的SQL
has_many :movies, :through => :movie_people, :select => 'distinct movies.*'
    

要回复问题请先登录注册