答えは、has_many:throughを使用した単一テーブル継承にあることがわかりました。
class Project < ActiveRecord::Base
has_many :projects_users, :dependent => :destroy
has_many :users, :through => :projects_users, :dependent => :destroy
has_one :admin, :through => :projects_users, :source => :user, :conditions => {:type => "Admin"}
has_one :supervisor, :through => :projects_users, :source => :user, :conditions => {:type => "Supervisor"}
has_many :operators, :through => :projects_users, :source => :user, :conditions => {:type => "Operator"}
validates_presence_of :name
validates_associated :admin
def admin_attributes=(attributes)
# build an admin object and apply to this relation
end
def supervisor_attributes=(attributes)
# build a supervisor object and apply to this relation
end
def operator_attributes=(operator_attributes)
operator_attributes.each do |attributes|
# build an operator object for each set of attributes and apply to this relation
end
end
end
class User < ActiveRecord::Base
has_many :projects_users, :dependent => :destroy
has_many :projects, :through => :projects_users, :dependent => :destroy
validates_presence_of :name
validates_associated :projects
end
class ProjectsUser < ActiveRecord::Base
belongs_to :project
belongs_to :user
end
class Admin < User
end
class Supervisor < User
end
class Operator < User
end
今、私たちは次のものを持つことができます
project1.users # User objects for admin, supervisor and operators
project1.admin # User object for Admin
project1.supervisor # User object for Supervisor
project1.operators # User objects for Operator
これらすべてを含む複雑なフォームは
<% form_for :project ...
<% fields_for "project[admin_attributes]", @project.admin do |admin_form|
...
<% @project.operators.each do |operator| %>
<% fields_for "project[operator_attributes][]", operator do |operator_form| %>
等々...