views:

33

answers:

2

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

A: 

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
neutrino
This is interesting, never knew Rails could do that.I ended up using:class Product has_many :prices, :dependent => :destroy, :class_name => 'ProductPrice'endThe obvious problem here was I needed to change all product_prices and bundle_prices associations I found throughout my software to prices...With the technique you just described, could you still use product_prices and bundle_prices associations?
jaycode
Not sure what you mean. By the way your solution seems clearer to me
neutrino
A: 

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

shingara
I would but this method won't work for all similar cases e.g. if model association isn't actually bundle_prices or package_prices.
jaycode