polymorphic association and setting default value for an asset

匆匆过客 提交于 2019-12-12 02:37:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!