La asignación de asociaciones polimórficas no funciona en ambas direcciones

I have a setup similar to the following one:

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

When assigning a sector to a project sectors list:

p = Project.first
s = Sector.first
p.sectors << s

... results in the the following SQL statement (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"

Doing it the other way round (assigning a project to the sectors project list:

p = Project.first
s = Sector.first
s.projects << p

... does the assignment correctly (goal_type is assigned):

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"

My question is: Why does the assignment is not working in the first case?

Mi configuración: Rails 2.3.14, Ruby 1.8.7

preguntado el 08 de noviembre de 11 a las 09:11

1 Respuestas

You clearly define that a Project's Sector deberán have "goal_type => 'Sector" (in the conditions on the association) whereas there is no such specification when going the other way.

if you put conditions on the other side then it'll work that way too.

respondido 08 nov., 11:16

Hm, how should this condition look like? My example was inspired by the following blog post: blog.hasmanythrough.com/2006/4/3/polymorphic-through - auralbee

I'm guessing (haven't tested it) that it would just be the same: ":conditions => "targets.goal_type = 'Sector'" - Taryn East

Thanks for your answer. Unfortunately, adding the condition does not make any difference. Arghhh, polymorphic associations drive me crazy ... ;-) - auralbee

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.