Dynamic class_name for has_many relationships

I am trying to make a has_many relation with the dynamic attribute class_name

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 are implemented using unidirectional table inheritance

Then I have Category ads as a nested set. I would like to indicate dynamically which type of ads belongs to the Category object.

Thanks for the help!

+7
ruby ruby-on-rails activerecord orm
source share
2 answers
 can't convert Proc into String 

means the rails expect a row

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

means you did not define item_type for the Class object

I believe that what you want here is not possible in this way.

I would use something like syntactic inheritance for declarations and its subtypes.

+3
source share

You can try

 def items item_type.constantize.where(category_id: id) end 
+5
source share

All Articles