ruby-on-rails 具有has_many关联的Rails自联接

s8vozzvw  于 2022-11-19  发布在  Ruby
关注(0)|答案(2)|浏览(183)

我正在尝试用Rails编写一个类似IMDB的应用程序。
我已经创建了电影模型。每部电影都有许多电影推荐(也是电影的示例)。
我不知道如何添加“has_many”关联、如何编写迁移文件或如何向每部电影添加推荐的电影。

nzk0hqpo

nzk0hqpo1#

您有一个多对多关系,这意味着我们需要一个连接表Recommendation
使用生成器创建模型和迁移文件:

bin/rails generate model Movie
bin/rails generate model Recommendation

然后更新迁移:

# db/migrate/20221023063944_create_movies.rb
class CreateMovies < ActiveRecord::Migration[7.0]
  def change
    create_table :movies do |t|
      # TODO: add fields
    end
  end
end

# db/migrate/20221023064241_create_recommendations.rb
class CreateRecommendations < ActiveRecord::Migration[7.0]
  def change
    create_table :recommendations do |t|
      t.references :movie,             null: false, foreign_key: true
      t.references :recommended_movie, null: false, foreign_key: { to_table: :movies }
    end
  end
end

运行迁移:

bin/rails db:migrate

设置模型:

# app/models/movie.rb
class Movie < ApplicationRecord
  # NOTE: this is the relationship for join table
  has_many :recommendations, dependent: :destroy

  # NOTE: get movies from join table
  has_many :recommended_movies, through: :recommendations
  #       this ^ is the name of the relationship in `Recommendation` we want
end

# app/models/recommendation.rb
class Recommendation < ApplicationRecord
  belongs_to :movie

  # NOTE: our foreign key is `recommended_movie_id` which rails infers 
  #       from `:recommended_movie`, but we have to specify the class:
  belongs_to :recommended_movie, class_name: "Movie"
end

在控制台bin/rails console中进行测试:

>> 3.times { Movie.create }
>> Movie.first.recommended_movies << [Movie.second, Movie.third]
>> Movie.first.recommended_movies
=> [#<Movie:0x00007f15802ec4c0 id: 2>, #<Movie:0x00007f15802ec3d0 id: 3>]

或类似于:

>> Movie.second.recommendations << Recommendation.new(recommended_movie: Movie.first)
>> Movie.second.recommended_movies
=> [#<Movie:0x00007f158215ef20 id: 1>]
  • 网址:guides.rubyonrails.org/association_basics.html#the-has-many-through-association*
  • 网址:guides.rubyonrails.org/association_basics.html#self-joins*
yptwkmov

yptwkmov2#

创建迁移时,需要定义要分配的模型引用

create_table :student do |t|
 t.references :class, foreign_key: true
end

这里我告诉我的class表将student的主键存储为外键。迁移后,class中将有一个名为student_id的列,它存储student表的pk。然后,我将在class模型文件中定义一个关联

class student < ApplicationRecord
  belongs_to :class
end

这将有助于我查询,以便我可以编写

student= Student.find 'student_id'
class = student.class

这将返回该学生的类。对于has_many,过程是相同的,但它将返回数组

相关问题