Rails:从现有表创建模型?

编程入门 行业动态 更新时间:2024-10-28 02:34:20
本文介绍了Rails:从现有表创建模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经从不同的项目创建了表.他们的名字的格式类似于 aaa_bbb_ccc_ddd(所有非复数和某些部分不是约定词).通过阅读 这个.但现在我必须制作实际模型.我查看了 RMRE,但他们在我的表上强制执行 ActiveRecord 约定并更改了它们的名称,我不想这样做,因为其他应用程序依赖于这些表.

I have tables already created from a different project. Their names are formatted like aaa_bbb_ccc_ddd (all non plural and some parts aren't a convention word). I have successfully created a schema from the database by reading this. But now I have to make the actual models. I've looked at RMRE, but they enforce the ActiveRecord convention on my tables and change their names, which I don't want to do because other apps depend on those tables.

从现有表自动创建模型和架构的最佳方法是什么?

What is the best way to automatically create models and a schema from existing tables?

推荐答案

只是一个理论,不确定这在实际应用中如何工作:

just a theory, not sure how this would work in real app:

create models 命名为 ActiveRecord 约定需要,例如对于表 aaa_bbb_ccc_ddd 你将创建一个模型 AaaBbb> 并将此模型映射到您的表:

create models named as ActiveRecord convention requires, for example for table aaa_bbb_ccc_ddd you'll create a model AaaBbb and map this model to your table:

class AaaBbb < ActiveRecord::Base self.table_name = "aaa_bbb_ccc_ddd" end

或更人性化的例子:

class AdminUser < ActiveRecord::Base self.table_name = "my_wonderfull_admin_users" end

现在你将有 AaaBbb 作为路由中的资源,这意味着你将有一个像:

Now you'll have AaaBbb as resource in routes meaning you'll have a url like:

.../aaa_bbb/...

如果你想在 url 中使用表名,我想你可以重写路由:

and if you want to use the table name name in url I guess you could rewrite the route:

get 'aaa_bbb_ccc_ddd/:id', "aaa_bbb#show", as: "aaa_bbb"

再说一次,这只是一个可能对你有帮助的理论.我还没有处理过这样的案例,但会从这个开始.

again, just a theory that might help you out. I haven't worked with such cases yet but would've start from this.

编辑

从数据库自动化模型创建:

github/bosko/rmre

但我认为这将按照 Rails 约定创建具有奇怪名称的模型,您必须将其用作应用程序中的资源.

but I think this will create models by rails convention with wierd names that you'll have to use as resource in your app.

我在 SO 上找到的一个很好的模板,以防您想使用与表名不同的模型名:

A good template that I found on SO in case you want to use a model name different from table name:

class YourIdealModelName < ActiveRecord::Base self.table_name = 'actual_table_name' self.primary_key = 'ID' belongs_to :other_ideal_model, :foreign_key => 'foreign_key_on_other_table' has_many :some_other_ideal_models, :foreign_key => 'foreign_key_on_this_table', :primary_key => 'primary_key_on_other_table' end

更多推荐

Rails:从现有表创建模型?

本文发布于:2023-10-20 12:54:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1511024.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模型   Rails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!