ruby-on-rails – 如何在保存多态对象的父级之前获取它?
发布时间:2020-12-17 02:59:43 所属栏目:百科 来源:网络整理
导读:我有一个标准的多态关系,我需要在保存它之前知道它的父亲是谁. Class Picture AR::Base belongs_to :attachable,:polymorphic = trueendClass Person AR::Base has_many :pictures,:as = :attachableendClass Vehicle AR::Base has_many :pictures,:as = :at
我有一个标准的多态关系,我需要在保存它之前知道它的父亲是谁.
Class Picture < AR::Base belongs_to :attachable,:polymorphic => true end Class Person < AR::Base has_many :pictures,:as => :attachable end Class Vehicle < AR::Base has_many :pictures,:as => :attachable end 我正在通过Paperclip上传图片,我构建了一个处理器,需要对不同的图片做不同的事情(即人物图片应该有宝丽来外观和车辆图片应该有覆盖).我的问题是,在图片保存之前,我不知道它是否与人或车辆相关联. 我尝试在Person&中加入一个“标记”.车辆,以便我可以告诉他们appart,但当我在Paperclip处理器时,我唯一看到的是Picture类. :(我的下一个想法是爬上堆栈试图让父母打电话,但这对我来说似乎很臭.你会怎么做? 解决方法
您应该能够从多态关联中获取它.
Class Picture < AR::Base belongs_to :attachable,:polymorphic => true before_create :apply_filter private def apply_filter case attachable when Person #apply Person filter when Vehicle #apply Vehicle filter end end end 或者,您可以问它关联类型,因此它不必构建和比较对象,而只是进行字符串比较. Class Picture < AR::Base belongs_to :attachable,:polymorphic => true before_create :apply_filter private def apply_filter case attachable_type when "Person" #apply Person filter when "Vehicle" #apply Vehicle filter end end end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |