问题
Newbie question. I have the following models:
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
My asset has a property called description. If the assetable_type is a "MenuItem" and the description is nil, I'd like the description to be the associated menu_item's body. How would I do this?
thx
回答1:
class Asset < ActiveRecord::Base
before_save :set_description
private
def set_description
self.description ||= assetable.body if assetable.is_a?(MenuItem)
end
end
Or modify the accessor
def description
return self[:description] unless self[:description].blank?
assetable.description if assetable.is_a? MenuItem
end
来源:https://stackoverflow.com/questions/8722140/polymorphic-association-and-setting-default-value-for-an-asset