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
2条答案
按热度按时间nzk0hqpo1#
您有一个多对多关系,这意味着我们需要一个连接表
Recommendation
。使用生成器创建模型和迁移文件:
然后更新迁移:
运行迁移:
设置模型:
在控制台
bin/rails console
中进行测试:或类似于:
yptwkmov2#
创建迁移时,需要定义要分配的模型引用
这里我告诉我的class表将student的主键存储为外键。迁移后,class中将有一个名为student_id的列,它存储student表的pk。然后,我将在class模型文件中定义一个关联
这将有助于我查询,以便我可以编写
这将返回该学生的类。对于has_many,过程是相同的,但它将返回数组