ruby-on-rails - has_many 关系的动态类名

标签 ruby-on-rails ruby activerecord orm

我正在尝试使 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/

相关文章:

java - 操作系统对 Ruby 开发有重大影响吗?

ruby-on-rails - rails : has_many through with polymorphic association - will this work?

ruby-on-rails - 如何从序列化为 JSON 的 ActiveModel 对象恢复关联类?

ruby-on-rails - Redmine 慢速 View 渲染

ruby-on-rails - ruby on Rails 中的 sum() 或 group() 虚拟属性

ruby-on-rails - 从 View 中无法访问帮助程序类

Codeigniter 使用连接表删除数据

ruby-on-rails - :symbol to Constant in rails

Ruby 语法、嵌套模块或类

html - 动态更改/插入登录页面的 HTML 和 css