Wednesday, March 07, 2007

Modeling the domain in database and Rails

第一步,Diagraming the domain:
1,先把domain都列出来,包括属性。
2,然后用一个个的方块表示出来,就像UML那样,但是不要那么复杂。而且不要用工具来做这件事情,就用铅笔在纸上画出来。

第二步,Initializing the databases:
1,使用root用户创建为该应用创建一个专门的用户,比如dillone。
2,创建一个schema,命名和application的名字一样,只不过字母都小写,比如comeback。
3,赋予dillone对于comeback的读写等权限。
4,使用dillone登陆MySQL,在comeback下创建三个库comeback_development, comeback_production, and comeback_test。遵循Ruby on Rails的命名规范。

第三步,Designing and creating the database tables:
1,创建一个create_tables.sql文件,把要创建的数据库表都用SQL写好。
2,创建一个insert_data.sql文件,把要注入的数据都准备这里,写好SQL语句。
3,创建一个drop_tables.sql文件,用来清除数据库表。
我把这三个文件SQL文件作为“标配”放在每个Rails app的db目录下。
注意:严格写Rails-friendly SQL:

  • Each entity gets a table in the database named after it, but in the plural.
  • Each such entity-matching table has a field called id, which contains aunique integer for each record inserted into the table.
  • Given entity x and entity y, if entity y belongs to entity x, then table y has a field called x_id.
  • The bulk of the fields in any table store the values for that entity’s simple properties (anything that’s a number or a string).
  • 数据库表名全部用小写,字段名全部小写,多词的名字中间用_连接,字段类型也用全部小写,例如:tagsiddescriptionpicturesvarchardatetimeopinion_idfk_op_picture
  • SQL语句中的关键字用全部大写,例如:CONSTRAINTPRIMARY KEYFOREIGN KEYCREATENOT NULLREFERENCESDROP

第四步,Composing the config/database.yml file:
development:
adapter: mysql
database: comeback_development
username: root
password:
host: localhost

test:
...

production:
...
注意:在使用rails appname命令创建一个新应用的时候,appname最好都是小写英文字母,不要首字母大写。这样在这个文件中生成的database: comeback_development 就会是小写的。如此,就与数据库名的大小写一致起来了。

第五步,Writing the Rails model files:
1,Rails creates models semi-automatically. From the top level of the application directory, issue the following commands:
$ ruby script/generate model work
$ ruby script/generate model edition
$ ruby script/generate model composer
You’ll find the three files work.rb, edition.rb, composer.rb in the app/models directory. 这些文件中的内容看上去只是empty definitions of Ruby classes,但实际上they have facilities for setting and retrieving all the entity properties. Rails endows them with those facilities automatically。
2,You need to add directives that tell Rails about the associations between entities—the details of the has and belongs_to relationships.

No comments: