翻译整理自:http://guides.rubyonrails.org/v3.2.13/association_basics.html
想吐槽一句,http://guides.ruby-china.org/ 翻译地太慢了!!!
csdn 复制过来格式都有误啊,改格式改了好几遍了。烦心。。。。
什么时候能支持markdown呢-。-
Rails支持以下6种关联类型:
class Order < ActiveRecord::Base belongs_to :customer end
class Supplier < ActiveRecord::Base has_one :account end
class Customer < ActiveRecord::Base has_many :orders end
class Physician < ActiveRecord::Base has_many :appointments has_many :patients,:through => :appointments end class Appointment < ActiveRecord::Base belongs_to :physician belongs_to :patient end class Patient < ActiveRecord::Base has_many :appointments has_many :physicians, :through => :appointments end
class Supplier < ActiveRecord::Base has_one :account has_one :account_history, :through => :account end class Account < ActiveRecord::Base belongs_to :supplier has_one :account_history end class AccountHistory < ActiveRecord::Base belongs_to :account end
class Assembly < ActiveRecord::Base has_and_belongs_to_many :parts end class Part < ActiveRecord::Base has_and_belongs_to_many :assemblies end
class Supplier < ActiveRecord::Base has_one :account end class Account < ActiveRecord::Base belongs_to :supplier end
class CreateSuppliers < ActiveRecord::Migration def change create_table :suppliers do |t| t.string :name t.timestamps end create_table :accounts do |t| t.integer :supplier_id t.string :account_number t.timestamps end end end
class Picture < ActiveRecord::Base belongs_to :imageable, :polymorphic => true end class Employee < ActiveRecord::Base has_many :pictures, :as => :imageable end class Product < ActiveRecord::Base has_many :pictures, :as => :imageable end
class Employee < ActiveRecord::Base has_many :subordinates, :class_name => "Employee", :foreign_key => "manager_id" belongs_to :manager, :class_name => "Employee" end