Rails开发细节(七)ActiveRecord Associations关联2013-12-111.为什么需要关联很多时候,比如说电子商务中的用户和订单,一个用户会有很多的订单,一个订单只属于一个用户,这就是一种关联。在创建订单的时候需要用户主键作为外键,删除用户的的同时需要删除用户的订单。在rails中可以向下面这样订单关联。
class Customer < ActiveRecord::Base has_many :orders, :dependent => :destroy end class Order < ActiveRecord::Base belongs_to :customer end
就可以像下面这样创建订单,删除用户。
@order = @customer.orders.create(:order_date => Time.now)@customer.destroy
2.关联的类型有下面6中关联。belongs_tohas_onehas_manyhas_many :throughhas_one :throughhas_and_belongs_to_many2.1.belongs_tobelongs_to是一种一对一的关联。表达一种属于的关系。就像一个订单只能属于个用户。在订单表会有一个字段存储用户主键,这个字段是订单表的外键。
class Order < ActiveRecord::Base belongs_to :customer end
2.2.has_onehas_one也是一种一对一的关联。表达一种有一个的关系。就像一个供应商只能有一个账户。账户表有一个供应商主键,是账户表的外键。
class Supplier < ActiveRecord::Base has_one :account end
2.3.has_manyhas_many是一种一对多的关联。表达有多个的关系。就像一个用户有多个订单。
class Customer < ActiveRecord::Base has_many :orders end
has_many关联的名称需要使用复数形式。