gpt4 book ai didi

ruby-on-rails - 如何使用 arel/关系代数和 has_many :through 获取不同的值

转载 作者:行者123 更新时间:2023-12-03 17:33:22 25 4
gpt4 key购买 nike

<分区>

当我尝试显示一个人参演的所有电影,并且他们在一部电影中担任多个角色(导演、编剧、 Actor )时,我会得到该电影的多行。如果我添加 .select('DISTINCT id') 或 movies.* 来尝试消除重复项,我会收到以下错误:

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 JOIN movie_people ON movies.id = movie_peop' at line 1: SELECTmovies.*, DISTINCT id FROMmoviesINNER JOINmovie_peopleONmovies.id =movie_people.movie_id WHERE ((movie_people`.person_id = 601619)) ORDER BY title LIMIT 18 OFFSET 0

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

应用/ Controller

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
导演:迈克尔·摩尔
编剧:迈克尔摩尔
Actor :迈克尔·摩尔乔治·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 年)

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com