Adding items to a collection associated w/ has_many :through


Quick review on has_many :through behavior.

I have the following model setup. X and Z are related many-to-many via
a bi-directional has_many :through relationship (Y is the join model).

X has_many Y
X has many Z :through => Y

Y belongs_to X
Y belongs_to Z

Z has_many Y
Z has_many X :through => Y

Note that non-standard foreign key names are used between both (X and Y)
and (Y and Z).

If I have an AR instance of a X and a Z (say @x and @new_z), shouldn’t I
just be able to do

@x.zs << @new_z and the appropriate record in Y should be created to
link them?

I always seem to have to do this instead to get this to work:

@x.ys.create(:z_identifier => @new_z).

I feel like the first statement is much clearer (“add a new z to x’s
collection of z’s”) instead of (“create a new x-z mapping record”).


This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs