问题
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

回答1:
Here we go :
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
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 ...
If you don't want indexes by default, just generate using model_name_id:integer
like serie_id:integer
(Note the singular form here)
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
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.
回答2:
I changed a view of your field names so rails can automatically create the table refrences (instead of id_categories
it should be category_id
aso...).
rails g scaffold user email:string password:string (will most likely be password_digest:string)
rails g scaffold category name:string
rails g scaffold post title:string body:string category_id:integer user_id:integer
rails g scaffold tags_posts post_id:integer tag_id:integer
rails g scaffold serie name:string website:string
rails g scaffold tag name:string
rails g scaffold tags_series tag_id:integer series_id:integer
As a personal preference, I would also not use tags_posts
as a table name, I would call it tagging
(s) as well as tags_series
would be link(s)
or something else.
I recommend you to take a look at http://guides.rubyonrails.org/migrations.html. It should clear up a lot about naming conventions, models, and migrations.
来源:https://stackoverflow.com/questions/13176946/how-can-i-generate-this-schema-with-rails