Rails:作为模型的数据库结构

发布于 2024-12-19 14:33:30 字数 361 浏览 0 评论 0原文

所以这可能听起来有点尴尬,但我希望将数据库结构(表、fkey、列)作为 Rails 模型的投影,例如

Table < ActiveModel 

响应调用

Table.find_by_name('Account').columns.each 

等的模型。有没有 gem 实现类似的功能?

更新:

基本上有一个项目可以查询一些远程开放数据源(如世界银行)并动态生成表格,这是由数据库完成的(是的,听起来很有趣)。事实上,我必须显示给定查询中涉及的表,区分哪些是本地的,哪些是刚刚生成的,还绘制外键和列。

So this may sound a bit awkward, but I would like to have the database structure (tables, fkeys, columns) as a projection on Rails models e.g. the model

Table < ActiveModel 

which would respond to call like

Table.find_by_name('Account').columns.each 

and so on. Is there any gem implementing something similar?

Update:

Basically there is a project that would query some remote open data sources (like world bank) and generate tables on the fly, and this is done by the database (yeah, sounds funny). The fact is that I have to show the the tables involved in a given query, distinguish which of them are local and which have just been generated, also draw the foreign keys and the columns.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

枫以 2024-12-26 14:33:30

只是一个想法:

module Table

  def self.find_by_name(name)
    return const_get(name) if const_defined?(name)

    model = Class.new(ActiveRecord::Base)
    model.set_table_name name.to_s.underscore.pluralize # sets the table
    const_set(name, model)

    model.column_names.each do |name|
      if name =~ /(\w+)_id$/
        model.belongs_to $1.to_sym
      end
    end

    model

  end

end

我真的不知道它是否有效以及您会遇到什么边缘情况。这个解决方案不适合胆小的人,您应该真正了解 Ruby 元编程才能使其发挥作用。

我希望这能给你一些启发:)

Just an idea:

module Table

  def self.find_by_name(name)
    return const_get(name) if const_defined?(name)

    model = Class.new(ActiveRecord::Base)
    model.set_table_name name.to_s.underscore.pluralize # sets the table
    const_set(name, model)

    model.column_names.each do |name|
      if name =~ /(\w+)_id$/
        model.belongs_to $1.to_sym
      end
    end

    model

  end

end

I don't really know if it'll work and what edge cases you'll run into. This solution is not for the faint-hearted and you should really know Ruby metaprogramming to make it work.

I hope this will give you some inspiration :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文