我的设置类似于以下设置:
class Project < ActiveRecord:Base
has_many :targets
has_many :sectors, :through => :targets, :source => :sector, :conditions => "targets.goal_type = 'Sector'"
has_many :departments, :through => :targets, :source => :department, :conditions => "targets.goal_type = 'Department'"
end
class Target < ActiveRecord:Base
belongs_to :project
belongs_to :goal, :polymorphic => true
belongs_to :sector, :class_name => 'Sector', :foreign_key => "goal_id"
belongs_to :department, :class_name => 'Department', :foreign_key => "goal_id"
end
class Sector < ActiveRecord:Base
has_many :targets, :as => :goal
has_many :projects, :through => :targets, :conditions => "targets.goal_type = 'Sector'"
end
class Department < ActiveRecord:Base
has_many :targets, :as => :goal
has_many :projects, :through => :targets, :conditions => "targets.goal_type = 'Department'"
end
将某个部门分配到项目部门列表时:
p = Project.first
s = Sector.first
p.sectors << s
...导致以下SQL语句( goal_type IS NULL ):
INSERT INTO "targets" ("created_at", "updated_at", "goal_type", "project_id", "goal_id") VALUES('2011-11-08 08:53:03.166295', '2011-11-08 08:53:03.166295', NULL, 86, 18) RETURNING "id"
反之亦然(将项目分配到扇区项目列表:
p = Project.first
s = Sector.first
s.projects << p
...正确分配( goal_type已分配):
INSERT INTO "targets" ("created_at", "updated_at", "goal_type", "project_id", "goal_id") VALUES('2011-11-08 09:01:46.663663', '2011-11-08 09:01:46.663663', 'Sector', 86, 18) RETURNING "id"
我的问题是:为什么作业在第一种情况下不起作用?
我的设置:Rails 2.3.14,Ruby 1.8.7
答案 0 :(得分:1)
你清楚地定义了一个项目的扇区必须具有“goal_type =&gt;'扇区”(在关联的条件下),而在走另一条路时没有这样的规范。
如果你把条件放在另一边,那么它也会这样。