rails 多对多关系多表查询

发表于:,更新于:,By Sally
大纲
  1. 1. model的关系
  2. 2. 查询某一个supervisor的所有decoartingcases

model的关系

  • Decoratingcase
1
2
has_many :supervisor_operations
has_many :supervisors, :through => :supervisor_operations
  • Supervisor
1
2
has_many :supervisor_operations
has_many :decoratingcases, :through => :supervisor_operations
  • SupervisorOperation
1
2
belongs_to :decoratingcase
belongs_to :supervisor

查询某一个supervisor的所有decoartingcases

  • 先查处所有的supervisor_operations
1
supervisor_operations = SupervisorOperation.where(:supervisor_id => params[:supervisor_id])
  • 再查处对应supervisor的decoratingcase_id

返回的是一个数组,包含所有decoratingcase_id,eg:[11, 26, 26, 27, 11, 28, 29, 11, 27, 27, 11, 30, 31, 32, 33, 49, 50]

1
decoartingcase_ids = supervisor_operations.map(&:decoratingcase_id)
  • 获得所有的decoratingcases
1
Decoratingcase.where(id:decoratingcase_ids)
  • 连接起来的写法
1
2
supervisor_decorating = SupervisorOperation.where(:supervisor_id => params[:supervisor_id])
@decoratingcases = Decoratingcase.where(id:supervisor_decorating.map(&:decoratingcase_id))