Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/52.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 多态关联值得吗?_Ruby On Rails - Fatal编程技术网

Ruby on rails 多态关联值得吗?

Ruby on rails 多态关联值得吗?,ruby-on-rails,Ruby On Rails,我正在开发的应用程序需要有“照片前”和“照片后”。现在数据库中有两个独立的表。我正在考虑合并这两个,这样看起来就像这样: create_table :photos do |t| t.string :image t.string :photographable_type end 也许在我的模型里有这样的东西 has_many :before_photos, class_name: 'Photo', as: :photographable has_many :after_pho

我正在开发的应用程序需要有“照片前”和“照片后”。现在数据库中有两个独立的表。我正在考虑合并这两个,这样看起来就像这样:

create_table :photos do |t|
    t.string  :image
    t.string  :photographable_type
end
也许在我的模型里有这样的东西

has_many :before_photos, class_name: 'Photo', as: :photographable
has_many :after_photos, class_name: 'Photo', as: :photographable
我以前从未使用过多态关联,我有点困惑。有人能告诉我做这件事的正确方法并解释一下吗


提前感谢

我认为您可以使用条件的
has\u许多
而不是像这样的多态关联:

class PhotoOwner < ActiveRecord::Base
  has_many :before_photos, -> { where some_field: true }, class_name: 'Photo'
  has_many :after_photos, -> { where some_field: false }, class_name: 'Photo'
end
class PhotoOwner{where some_field:true},类名:'Photo'
有很多:在照片之后,->{where some_field:false},类名称:'Photo'
结束

从这里获取:,部分“自定义查询”

这里有一个很棒的railscast:。你能解释一下照片前后的情况吗?他们是模特吗?在提及之前/之后是什么?如果这只是同一张图片的两个版本,一个是之前的,另一个是之后的,我甚至不会使用两个模型。我会使用两个图像列/上传器。如果可拍照类型的列表可能会增加,或者两个模型之间存在大量重复,那么多态性就有意义了。