在Rails中,模型引用(Model Association)指的是建立不同模型之间的关系。向现有模型添加引用意味着在已经存在的模型之间建立关联关系。
Rails支持以下几种主要关联类型:
rails generate migration AddReferenceToExistingModel existing_model_id:references
class AddReferenceToExistingModel < ActiveRecord::Migration[6.1]
def change
add_reference :existing_models, :related_model, foreign_key: true
# 或者明确指定列名
# add_column :existing_models, :related_model_id, :integer
# add_foreign_key :existing_models, :related_models
end
end
rails db:migrate
# 在ExistingModel模型中
class ExistingModel < ApplicationRecord
belongs_to :related_model
end
# 在RelatedModel模型中
class RelatedModel < ApplicationRecord
has_one :existing_model
# 或者如果是has_many关系
# has_many :existing_models
end
原因:表中已有数据,但引用的ID不存在于关联表中
解决方案:
# 在迁移中使用null: true允许空值
add_reference :existing_models, :related_model, foreign_key: true, null: true
解决方案:
class ExistingModel < ApplicationRecord
belongs_to :owner, class_name: "User", foreign_key: "user_id"
end
class User < ApplicationRecord
has_many :owned_models, class_name: "ExistingModel", foreign_key: "user_id"
end
解决方案:
# 迁移
add_reference :existing_models, :commentable, polymorphic: true
# 模型
class ExistingModel < ApplicationRecord
belongs_to :commentable, polymorphic: true
end
class Article < ApplicationRecord
has_many :existing_models, as: :commentable
end
class Photo < ApplicationRecord
has_many :existing_models, as: :commentable
end
class Comment < ApplicationRecord
belongs_to :article, touch: true
end
通过正确添加模型引用,可以大大简化数据操作和查询逻辑,提高应用的可维护性和性能。
没有搜到相关的文章