开发者

Polymorphism on ActiveRecord model

I have two models, say Product and Bundle.

products table is related to product_prices table and bundles to bundle_prices (need to make these separations to support multiple currencies)

Obviously both Product and Bundle share some similar methods like get_price

I have make both Product and Bundle pointing to an abstract Class for this, lets say SellableItem.

So now I have:

class Product < SaleableItem

class Bundle < SaleableItem

class SellableItem < ActiveRecord::Base

My question is,开发者_开发问答 how do I add function in SellableItem like this for instance?

def get_price(currency = '')
  #get from bundle_prices if object is Bundle or product_prices if object is Product
end

Any help is deeply appreciated


Well, in the same way you can define a method in SellableItem and implement it in Product and Bundle, that will return the type of association you need

class Product 
  def prices_association
    :product_prices
  end
end

class Bundle 
  def prices_association
    :bundle_prices
  end
end

and then

def get_price(currency = '') 
  self.send(prices_association).find(:conditions => ...)
end


Why don't define a GetPrice module with this method


module GetPrice
  def get_price(currency = '')
    send("#{self.class.to_s.downcase}_prices")
  end
end

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜