rails多态关联,父类无法正常工作

时间:2014-11-18 15:01:23

标签: ruby-on-rails ruby polymorphic-associations

我有一个多态模型资产,用于不同的模型。它适用于所有其他型号吧。与所讨论的模型的唯一区别是它继承自STI的父类。

class QeopPage < Page

end 

class Page < ActiveRecord::Base
   include Assetable
   has_many :assets, as: :assetable 
end

module Assetable
#this processes attachments, i have truncated to show only the important bits.

  at="#{thing.to_s.singularize}_attachment".to_sym
  alt="#{thing.to_s.singularize}_attachment_alt".to_sym
  att="#{thing.to_s.singularize}_attachment_title".to_sym
  atr="#{thing.to_s.singularize}_attachment_remove".to_sym
  atu="#{thing.to_s.singularize}_attachment_url".to_sym
  if self.respond_to?(thing) and self.respond_to?(at) and self.send(at).present?
    a=Asset.new(:attachment=>self.send(at),:title=>self.send(att),:alt=>self.send(alt), assetable_type: self.class.name, assetable_id: self.id, url: self.send(atu))
    if a.alt.present? and a.title.blank?
      a.title=a.alt
    elsif a.alt.blank? and a.title.present?
      a.alt=a.title
    end
    if a.save
      self.send("#{at}=",nil)
      self.send("#{alt}=",nil)
      self.send("#{att}=",nil)
      self.send("#{atr}=",nil)
      self.send("#{atu}=",nil)
      self.send("#{thing.to_s.pluralize.to_sym}=",self.send("#{thing.to_s.pluralize.to_sym}")+[a])
    else
      errors.add(thing,a.errors.full_messages.join(','))
      return false
    end

问题是尽管所有数据都存储正确,但没有关联。

>> instance
=> #<QeopPage id: 220, venue_id: 203, nav_title: "about legacy", title: "legacy"
>> instance.assets
=> #<ActiveRecord::Associations::CollectionProxy []>

>> Asset.last
=> #<Asset id: 9619, assetable_type: "QeopPage", assetable_id: 220, url: nil>


>> instance.id == Asset.last.assetable_id && instance.class.name == Asset.last.assetable_type
=> true

上述课程中有很多内容,所以我不确定该帖子中包含哪些内容。如果您还有其他需求,请询问。

0 个答案:

没有答案