常用命令
- rails new new_app
- cd new_app
- rake db:create
- rails server
- rails generate controller Blog action1 action2
- rails generate scaffold Product title:string description:text
-
rails generate model Comment commenter:string body:text post:references
- rake db:migrate
- rake db:rollback
- rails test:units
- rails console
约定
rails中有很多的约定,正是这些约定帮我们节省了时间,让我们很清晰的明白项目的结构,文件的位置。
表名约定
表名默认使用model的复数形式,小写。例如:model是Sheep,默认的表名就是sheeps,如果我们想自定义一些其他名字,或者基于一个已经存在的数据表进行开发,不能修改这个数据表的名称,那么我们可以通过下面的代码来指定表的名称。
- class Sheep < ActiveRecord::Base
- self.table_name = "sheep"
- end
表主键的约定
默认主键名称id,整型,自增。在数据表中名称就是id,在model中也通过.id来访问。如果想指定其他名称,可以通过下面的代码实现。
- class LegacyBook < ActiveRecord::Base
- self.primary_ke = "isbn"
- end
通过上面的修改之后,数据表的主键列名称变为isbn,在model中也通过.isbn来访问。但是有一个地方例外,就是给主键赋值,还是需要使用id来赋值。
- book = LegacyBoo.new
- book.id = "1-214-985"
- book.title = "programming in ruby"
除了给主键赋值需要用id,其他时候都用指定的列名。
model的关系
表关系有三种:
one-to-one
one-to-many
many-to-many
在model中使用的声明有:has_one, has_many, belongs_to, has_and_belongs_to_many。
one-to-one
- class Order < ActiveRecord::Base
- has_one :invoice
- end
- class Invoice < ActiveRecord::Base
- belongs_to :order
- end
一个订单有一个发票抬头,一对一的关系。
有一条很重要:包含外键的表,一定会有一个belongs_to的声明。
one-to-many
- class Order < ActiveRecord::Base
- has_many :line_items
- end
- class LineItem < ActiveRecord::Base
- belongs_to :order
- end
一个订单会有很多的item,一对多的关系。
many-to-many
- class Product < ActiveRecord::Base
- has_and_belongs_to_many :categories
- end
- class Category < ActiveRecord::Base
- has_and_belongs_to_many :products
- end
一个产品属于多个目录,一个目录包含多个产品,多对多的关系。除了products表和categories表,会有一个中间表categories_products(category_id, product_id)来存放这个关系。
我们也可以自己定义关系表,还可以存放一些其他信息,一些关于关系的信息。其实就是把多对多的关系拆分开,成为两个一对多的关系,这样也好理解些。