常用命令

 

 
  
  1. rails new new_app 
  2.  
  3. cd new_app
  4.  
  5. rake db:create
  6.  
  7. rails server 
  8.  
  9. rails generate controller Blog action1 action2
  10.  
  11. rails generate scaffold Product title:string description:text


  1.  rails generate model Comment commenter:string body:text post:references

 

  1. rake db:migrate
  2.  
  3. rake db:rollback
  4.  
  5. rails test:units
  6.  
  7. rails console 

约定

rails中有很多的约定,正是这些约定帮我们节省了时间,让我们很清晰的明白项目的结构,文件的位置。

表名约定

表名默认使用model的复数形式,小写。例如:model是Sheep,默认的表名就是sheeps,如果我们想自定义一些其他名字,或者基于一个已经存在的数据表进行开发,不能修改这个数据表的名称,那么我们可以通过下面的代码来指定表的名称。

 

 
  
  1. class Sheep < ActiveRecord::Base 
  2.  
  3.   self.table_name = "sheep" 
  4.  
  5. end 

表主键的约定

默认主键名称id,整型,自增。在数据表中名称就是id,在model中也通过.id来访问。如果想指定其他名称,可以通过下面的代码实现。

 

 
  
  1. class LegacyBook < ActiveRecord::Base 
  2.  
  3.   self.primary_ke = "isbn" 
  4.  
  5. end 

通过上面的修改之后,数据表的主键列名称变为isbn,在model中也通过.isbn来访问。但是有一个地方例外,就是给主键赋值,还是需要使用id来赋值。

 

 
  
  1. book = LegacyBoo.new 
  2. book.id = "1-214-985" 
  3. 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

 

 
  
  1. class Order < ActiveRecord::Base 
  2.   has_one :invoice 
  3. end 
  4.  
  5. class Invoice < ActiveRecord::Base 
  6.   belongs_to :order 
  7. end 

一个订单有一个发票抬头,一对一的关系。

有一条很重要:包含外键的表,一定会有一个belongs_to的声明。

one-to-many

 

 
  
  1. class Order < ActiveRecord::Base 
  2.   has_many :line_items 
  3. end 
  4.  
  5. class LineItem < ActiveRecord::Base 
  6.   belongs_to :order 
  7. end 

一个订单会有很多的item,一对多的关系。

many-to-many

 

 
  
  1. class Product < ActiveRecord::Base 
  2.   has_and_belongs_to_many :categories 
  3. end 
  4.  
  5. class Category < ActiveRecord::Base 
  6.   has_and_belongs_to_many :products 
  7. end 

一个产品属于多个目录,一个目录包含多个产品,多对多的关系。除了products表和categories表,会有一个中间表categories_products(category_id, product_id)来存放这个关系。

我们也可以自己定义关系表,还可以存放一些其他信息,一些关于关系的信息。其实就是把多对多的关系拆分开,成为两个一对多的关系,这样也好理解些。