新手问题。我有以下型号:
class Asset < ActiveRecord::Base
belongs_to :assetable, :polymorphic => true
#paperclip
has_attached_file :asset,
:hash_secret => "my-secret",
:url => "/images/:hash_:basename_:style.:extension",
:path => UPLOAD_PATH + "/:hash_:basename_:style.:extension",
:styles => { :medium => "300x300>", :thumb => "75x75>"
}
end
class Location < ActiveRecord::Base
has_many :assets, :as => :assetable, :dependent => :destroy
end
class MenuItem < ActiveRecord::Base
has_many :assets, :as => :assetable
end
我的资产有一个名为description的属性。如果assetable_type是“MenuItem”并且描述为nil,我希望描述是关联的menu_item的主体。我该怎么做?
THX
答案 0 :(得分:1)
class Asset < ActiveRecord::Base
before_save :set_description
private
def set_description
self.description ||= assetable.body if assetable.is_a?(MenuItem)
end
end
或修改访问者
def description
return self[:description] unless self[:description].blank?
assetable.description if assetable.is_a? MenuItem
end