RoR - Expressing Database Relationships

One-to-One Association:

*一个person只对应一个personal_info 

*一个personal_info只属于一个person

*belongs to用foreign key来链接

rails g model personal_info height:float weight:float person:references 

此外你同时也有2个method

build_personal_info(hash)
#=> 在数据库中创建record create_personal_info(hash)
#=> 在memory中创建record

#=> Both remove the previous reference in the DB

用于person的实例

你需要用 has_one/belongs_to 去建立1对1association

 One-to-Many Assoication:

*一个Person可能有1个或多个jobs

*但一个jobs只属于一个Person

belongs to的关系用foreign key来建立

rails g model job title company position_id person:references
#in model 

class Person < ActiveRecord::Base 
    has_one :personal_info 
    has_many :jobs 
end 

class Job < ActiveRecord::Base 
    belongs_to :person 
end 
person.jobs = jobs 
# 用新的array替换现有的jobs

person.jobs << job(s) 
# 添加新的jobs

person.jobs.clear 
# 将foreign key 设置为NULL, 解除这个person和jobs之间的关系

create!   where! 
#加了!才会提醒是否成功
# :dependent

class Person < ActiveRecord::Base 
    has_one :personal_info, dependent: :destroy     
 end 

# 这样删除person的时候同时会删除跟person相关的personal_info

Many-to-Many association:

*一个person可以有很多hobbies

*一个hobbies可以被很多person共享

has_many&belongs_to_many

#join table 

rails g model hobby name 

rails g migration create_hobbies_people person:references hobby:references

#生成Migration 
class CreateHobbiesPeople < ActiveRecord::Migration 
    def change 
        create_table :hobbies_people, id: false do |t| 
            t.references :person, index: true, foreign_key: true 
            t.references :hobby, index:true, foreign_key: true
        end    
    end
end 

#model 
class Person < ActiveRecord::Base 
    has_and_belongs_to_many :hobbies 
end 

class Hobby < ActiveRecord::Base
    has_and_belongs_to_many :people 
end

Many-to-Many 包含了2个model和3个migration

Join table只存在数据库中,不在ruby代码里面

Rich Many-to-Many assoiciation:

#SalaryRange Model and Migration 

rails g model salary_range min_salary:float max_salary:float job:references 

class CreateSalaryRanges < ActiveRecord::Migration 
    def change 
        create_table :salary_ranges do |t| 
            t.float :min_salary 
            t.float :max_salary
            t.references :job,  index: true, foreign_key: true 

            t.timestamps null: false 
        end    
    end 
 end

#model 

class Person < ActiveRecord::Base 
    has_many :jobs
    has_many :approx_salaries, through: :jobs, source: :salary_range

    def max_salary 
        approx_salaries.maximum(:max_salary)
    end
end

class Job < ActiveRecord::Base 
    belongs_to :person 
    has_one :salary_range 
end 

class SalaryRange < ActiveRecord::Base 
    belongs_to :job 
end 

猜你喜欢

转载自www.cnblogs.com/vixennn/p/10702882.html