[英]change type in polymorphic association in rails
我是Rails的新手,正在使用Rails多态关联,遇到一个问题,我有两个模型EmployeeTable和ProductTable。 两者在图片模型中都有一些图片
class Picture < ActiveRecord::Base
belongs_to :imageable, polymorphic: true
end
class EmployeeTable < ActiveRecord::Base
has_many :pictures, as: :imageable
end
class ProductTable < ActiveRecord::Base
has_many :pictures, as: :imageable
end
图片中有两列imagable_id和imagable_type。 当我在表中创建条目时,它将imagable_type存储为“ EmployeeTable”或“ ProductTable”。 我可以将这些名称更改为任何不同的名称,例如“员工”和“产品”。
提前致谢
要检索不带表的image_type,可以在模型中添加此方法。 保存时更改关联的模型名称将导致查询时出现问题
def neat_imageable_type
self.imageable_type.gsub("Table", "").downcase
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.