我正在尝试使 has_many 与动态 class_name 属性建立关系
class Category < ActiveRecord::Base
has_many :ads, :class_name => ( lambda { return self.item_type } )
end
或
class Category < ActiveRecord::Base
has_many :ads, :class_name => self.item_type
end
但是我有错误:
can't convert Proc into String
或
undefined method `item_type' for #<Class:0xb62c6c88>
编辑 我有两种不同类型的广告
LeaseAd
, RentAd
他们使用单表继承实现
然后我将 Category
广告作为嵌套集。我想动态指定哪种类型的广告属于 Category
对象。
感谢您的帮助!
最佳答案
你可以试试
def items
item_type.constantize.where(category_id: id)
end
关于ruby-on-rails - has_many 关系的动态类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3045254/