Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic class_name for has_many relations

I'm trying to make has_many relation with dynamic class_name attribute

class Category < ActiveRecord::Base
  has_many :ads, :class_name => ( lambda { return self.item_type } ) 
end

or

class Category < ActiveRecord::Base
  has_many :ads, :class_name => self.item_type
end

But i got errors:

can't convert Proc into String

or

undefined method `item_type' for #<Class:0xb62c6c88>

EDIT I have two different types of Ads

LeaseAd, RentAd they implemented using single table inheritance

Then i have Category of ads as nested set. I would like to specify dinamicly which type of ads belongs to Category object.

Thank you for any help!

like image 227
vooD Avatar asked Jun 15 '10 12:06

vooD


1 Answers

You can try

def items
  item_type.constantize.where(category_id: id)
end
like image 172
ZubKonst Avatar answered Oct 23 '22 02:10

ZubKonst