本文介绍了如何使用arel / relational代数和has_many获取不同值:through的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试显示一个人所处的所有电影,并且它们在一部电影中具有多个角色(导演,编剧,演员)时,该电影会显示多行。如果我添加.select('DISTINCT id')或movie。*以尝试消除重复,则出现以下错误:

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:

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

谢谢。

I don't know how to code the arel request correctly. Please help.
Thank you.

应用/控制器

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

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

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

标题:华氏9/11

年:2004

导演:迈克尔·摩尔

作家:迈克尔·摩尔

演员:迈克尔·摩尔George W. Bush

Title: Fahrenheit 9/11
Year: 2004
Director: Michael Moore
Writer: Michael Moore
Cast: Michael Moore George W. Bush

people / show .html.erb

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

Name: Michael Moore
Fahrenheit 9/11 (2004)
Fahrenheit 9/11 (2004)
Fahrenheit 9/11 (2004)

推荐答案

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

In Arel, uniq generates the appropriate select distinct SQL. I'm not sure how to add Arel to a has_many association, but in regular (controller) code it would be something like

@person.movies.uniq

请参见和

这篇关于如何使用arel / relational代数和has_many获取不同值:through的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 02:04