【问题标题】:Dynamicaly creating a model with a real DB as attribute of another model动态创建具有真实 ID 的模型作为另一个模型的属性
【发布时间】:2014-01-13 21:51:06
【问题描述】:

我有一个名为“tables”的表,里面有一个名为 table_name 的列。而且,在我的其他模式中的数据库上,我有这个表。喜欢:

db: tables
id  table_name  other_attributes
 1  minerals    ...
 2  animals     ...

db: minerals
id  name  type
 1  rock  nil
 2  sand  nil

这些表的结构不同。我想这样称呼我的模型:

> tab = Table.find(1)
> tab.elements.all
=> [ {id: 1, name: 'rock', type: nil}, {id: 2, name: 'sand', type: nil} ]

并在此 .elements 中使用任何类型的活动记录任务... 我没有找到任何方法,我找到的最接近的文章是:Rails 3/ActiveRecord: How to switch/change table name during request dynamically?

【问题讨论】:

  • 只要我的 2 美分,如果你不知道如何以“railsy”的方式做到这一点。您可以随时 ActiveRecord::Base.connection.execute("SQL query") 使用手动 SQL 查询创建表。

标签: ruby-on-rails ruby model ruby-on-rails-4


【解决方案1】:

我相信在您的情况下最好的方法是直接更新数据库。如果您不喜欢直接编写 SQL,可以依赖一些高级库,例如 Sequel,在这种情况下,它们与 ActiveRecord 强加的约定的耦合度稍低。

【讨论】:

  • 我直接写SQL没有问题,但正如Andrew Wei所说,我想用“railsy”的方式来做! :) 我会研究这个续集。
【解决方案2】:

如果您使用 PostgreSql,您可能对 hstore 感兴趣 - http://railscasts.com/episodes/345-hstore。使用 hstore(它存储 json)将大大简化您的数据库和应用程序:)

【讨论】:

    【解决方案3】:

    在这个问题之后的一段时间,我想(只是想,因为我不知道它是否真的正确)这是答案:

    class TableMaster < ActiverRecord::Base
      attr_accessor :db
      after_find do
        me = self
        me.db = Class.new ( ActiveRecord::Base ) do
            self.table_name = "schema." + me.tablename
        end
        true
      end
    end
    

    只要把它放在模型里面,另一个里面就会有一个功能齐全的 Active Record 模型。 我很高兴我得到了这个答案,但我仍然怀疑它是否真的正确。请给我一些建议。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 2011-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多