gpt4 book ai didi

ruby-on-rails - ruby on rails,has_many,定义多态关系的类名

转载 作者:行者123 更新时间:2023-12-04 18:12:44 24 4
gpt4 key购买 nike

这是我从旧数据库中移动数据的代码:

class Old < ActiveRecord::Base
establish_connection :old_version
self.abstract_class = true

class Recipe < self
set_table_name :recipes
has_many :uploaded_files, :as => :storage
end

class UploadedFile < self
set_table_name :uploaded_files
belongs_to :storage, :polymorphic => true
end
end

当我运行以下代码时
Old::Recipe.all.each do |recipe|
puts recipe.uploaded_files.to_sql
end

它执行此 SQL
SELECT `uploaded_files`.* FROM `uploaded_files`  WHERE `uploaded_files`.`storage_id` = 38 AND `uploaded_files`.`storage_type` = 'Old::Recipe'

问题是我得到:
`storage_type` = 'Old::Recipe'

但是我需要:
`storage_type` = 'Recipe'

如何更改多态关系的类?

has_many 的文档不给我答案。

最佳答案

最近我遇到了类似的问题,这是一个在 rails 4.2 中对我有用的解决方案:

class Recipe < self
set_table_name :recipes
has_many :old_files, -> (object) { unscope(where: :storage_type).where(storage_type: 'Recipe') }, class_name: 'UploadedFile'
end

您必须添加 unscope(:where)删除条件 uploaded_files.storage_type = 'Old::Recipe'从查询。

关于ruby-on-rails - ruby on rails,has_many,定义多态关系的类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10083667/

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