如何使用 Rails 生成此架构? [英] How can I generate this schema with Rails?

查看:42
本文介绍了如何使用 Rails 生成此架构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关系数据库的架构,我想在我的 Ruby on Rails 3.2.8 项目中为它生成脚手架.不过,我发现文档非常混乱,到目前为止我的努力都失败了,所以我的问题正是我将如何为以下架构生成所需的脚手架/模型:

I have a schema for a relational database, which I'd like to generate scaffolding for in my Ruby on Rails 3.2.8 project. I've found the documentation pretty confusing though, and my efforts so far have failed, so my question is exactly how I'd go about generating the needed scaffolding/models for the following schema:

USER
name:string
email:string
-----
has_many: posts

TAG
name:string
-----
belongs_to_and_has_many: series
belongs_to_and_has_many: posts

POST
title:string
body:text
-----
belongs_to_and_has_many: tags
belongs_to: user
belongs_to: category

SERIES
name:string
website:string
-----
belongs_to_and_has_many: tags

CATEGORY
name:string
-----
has_many: posts

推荐答案

我们开始:

rails g scaffold User email:string password:string
rails g scaffold Category name:string
rails g scaffold Post title:string body:text category:references user:references
rails g scaffold Tag name:string
rails g scaffold TagsPost post:references tag:references
rails g scaffold Serie name:string website:string
rails g scaffold TagsSerie serie:references tag:references

这里我使用 references 因为它具有自动为您在列上生成索引的额外好处.尽管数据库生成很好,但我建议您查看生成的实际 db/migrations 文件并添加更多索引等...

Here I'm using references because it has the added benefit of automatically generating an index on the column for you. Although the DB generation is nice, I suggest you review the actual db/migrations files generated and add more indexes etc ...

如果你不想要默认的索引,只需使用 model_name_id:integer 生成,就像 serie_id:integer(注意这里的单数形式)

If you don't want indexes by default, just generate using model_name_id:integer like serie_id:integer (Note the singular form here)

我还考虑将您的关联表重命名为单数:TagPostTagSerie 因为它是 TagSeriePost

I'd also consider renaming your association tables to be singular : TagPost and TagSerie since it's an association between a Tag and either a Serie or a Post

另请注意,在生成符合自动 Rails 的外键时,默认情况下它们将被命名为 model_name_id 而不是 id_users 正如您的架构提到的那样.所有这些都可以更改,但让 Rails 为您解决所有问题更容易.约定优于配置是 Rails 的一大优势.

Also beware, when generating automatic rails compliant foreign keys, they'll by default be named model_name_id and not id_users as your schema mentions. All of this can be changed but it's easier to make Rails figure out everything for you. Convention over configuration is one of the big strength of Rails.

这篇关于如何使用 Rails 生成此架构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆