Dynamic class_name for has_many relations

对着背影说爱祢 提交于 2019-12-10 13:04:35

问题


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!


回答1:


can't convert Proc into String

means that rails is expecting a String

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

means that you didn't define item_type for the Class-object

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

I would use something like singletable inheritance for the ads and its subtypes.




回答2:


You can try

def items
  item_type.constantize.where(category_id: id)
end


来源:https://stackoverflow.com/questions/3045254/dynamic-class-name-for-has-many-relations

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