Rails Study(9)Associations First Part

本文深入探讨了Rails框架中关联关系的概念及其在不同场景的应用,包括属于、拥有、多对多等类型,通过实例解析如何在模型间建立关联,并提供选择不同关联方式的指导。同时,介绍了聚合关联、通过关联、自关联等高级用法,以及如何优化数据库查询性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Rails Study(9)Associations First Part

1. Why Associations?
Without Associations, we will configure and use the models like this:
class Customer < ActiveRecord::Base
end
class Order < ActiveRecord::Base
end

When we want to create an order
@order = Order.create(:order_date => Time.now, :customer_id => @customer.id)

consider deleting a customer
@orders = Order.find_all_by_customer_id(@customer.id)
@orders.each do |order|
order.destroy
end
@customer.destroy

With association.
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. The Types of Associations
belongs_to
has_one
has_many
has_many :through
has_one :through
has_and_belongs_to_many

2.1 The belongs_to Association
Each order can be assigned to exactly one customer.
class Order < ActiveRecord::Base
belongs_to :customer
end

2.2 The has_one Association
one supplier has only one account.

class Supplier < ActiveRecord::Base
has_one :account
end

2.3 The has_many Association
You'll often find this association on the "other side" of a belongs_to association.
Customers have orders or not.

class Customer < ActiveRecord::Base
has_many :orders
end

2.4 The has_many :through Association
Consider a medical practice where patients make appointments to see physicians.
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

If a document has many sections, and a section has many paragraphs.

class Document < ActiveRecord::Base
has_many :sections
has_many :paragraphs, :through => :sections
end

class Section < ActiveRecord::Base
belongs_to :document
has_many :paragraphs
end

class Paragraph < ActiveRecord::Base
belongs_to :section
end

2.5 The has_one :through Association
Each supplier has one account, each account is associated with one account history.
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

2.6 The has_and_belongs_to_many Association
Application includes assemblies and parts, each assembly having many parts and each part appearing in many assembilies.
class Assembly < ActiveRecord::Base
has_and_belongs_to_many :parts
end

class Part < ActiveRecord::Base
has_and_belongs_to_many :assemblies
end

assemblies ------> assemblies_parts <----------- parts
id assembliy_id id
name part_id part_number

2.7 Choosing Between belongs_to and has_one
It makes more sense to say that a supplier owns an account than that an account owns a supplier.
class Supplier < ActiveRecord::Base
has_one :account
end

class Account < ActiveRecord::Base
belongs_to :supplier
end

2.8 Choosing Between has_many :through and has_and_belongs_to_many
The simplest rule of thumb is that you should set up a has_many :through relationship if you need to work with the
relationship model as an independent entity. If there is no need for relationship model, it may be simpler to set up
a has_and_belongs_to_many relationship.

2.9 Polymorphic Associations
You might have a picture model that belongs to either an employee model or a product model.

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

employees -------> pictures <---------------------products
id id id
name name name
imageable_id
imageable_type

The migration class can be:
class CreatePictures < ActiveRecord::Migration
def self.up
create_table :pictures do |t|
t.string :name
t.integer :imageable_id
t.string :imageable_type
t.timestamps
end
end
end

class CreatePicture < ActiveRecord::Migration
def self.up
create_table :pictures do |t|
t.string :name
t.references :imageable, :polymorphic => true
t.timestamps
end
end
end

2.10 Self Joins
Relationships such as between manager and subordinates.
class Employee < ActiveRecord::Base
has_many :subordinates, :class_name => "Employee", :foreign_key => "manager_id"
belongs_to :manager, :class_name => "Employee"
end

retrieve @employee.subordinates @employee.manager

3 Tips, Tricks, and Warnings
3.1 Controlling Caching
customer.orders #retrieves orders from the db
customer.orders.size #uses the cached copy of orders
customer.orders.empty? #uses the cached copy of orders
customer.orders(true).empty? #discards the cached, goes back to the db

3.2 Avoiding Name Collisions
attributes or connection are bad names for associations.

3.3 Updating the Schema
3.3.1 Creating Foreign Keys for belongs_to Associations
class Order < ActiveRecord::Base
belongs_to :customer
end

class CreateOrders < ActiveRecord::Migration
def self.up
create_table :orders do |t|
t.datetime :order_date
t.string :order_number
t.integer :customer_id
end
end
end

3.3.2 Creating Join Tables for has_and_belongs_to_many Associations
Creating the assemblies_parts table.

class CreateAssemblyPartJoinTable < ActiveRecord::Migration
def self.up
create_table :assemblies_parts, :id => false do |t|
t.integer :assembly_id
t.integer :part_id
end
end
end

3.4 Controlling Association Scope
classes in the same module

module MyApplication
module Business
class Supplier < ActiveRecord::Base
has_one :account
end

class Account < ActiveRecord::Base
belongs_to :supplier
end
end
end

module MyApplication
module Business
class Supplier < ActiveRecord::Base
has_one :account, :class_name => "MyApplication::Billing::Account"
end
end

module Billing
class Account < ActiveRecord::Base
belongs_to :supplier, :class_name => "MyApplication::Business::Supplier"
end
end
end

4. snip..

references:
http://guides.rubyonrails.org/association_basics.html
内容概要:文章详细介绍了ETL工程师这一职业,解释了ETL(Extract-Transform-Load)的概念及其在数据处理中的重要性。ETL工程师负责将分散、不统一的数据整合为有价值的信息,支持企业的决策分析。日常工作包括数据整合、存储管理、挖掘设计支持和多维分析展现。文中强调了ETL工程师所需的核心技能,如数据库知识、ETL工具使用、编程能力、业务理解能力和问题解决能力。此外,还盘点了常见的ETL工具,包括开源工具如Kettle、XXL-JOB、Oozie、Azkaban和海豚调度,以及企业级工具如TASKCTL和Moia Comtrol。最后,文章探讨了ETL工程师的职业发展路径,从初级到高级的技术晋升,以及向大数据工程师或数据产品经理的横向发展,并提供了学习资源和求职技巧。 适合人群:对数据处理感兴趣,尤其是希望从事数据工程领域的人士,如数据分析师、数据科学家、软件工程师等。 使用场景及目标:①了解ETL工程师的职责和技能要求;②选择适合自己的ETL工具;③规划ETL工程师的职业发展路径;④获取相关的学习资源和求职建议。 其他说明:随着大数据技术的发展和企业数字化转型的加速,ETL工程师的需求不断增加,尤其是在金融、零售、制造、人工智能、物联网和区块链等领域。数据隐私保护法规的完善也使得ETL工程师在数据安全和合规处理方面的作用更加重要。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值