has_many: through, :class_name, :foreign_key

Hello!

When we use has_many :through, is there a way to specify the name of
the class and the foreign key? This question pops up when the join
table has fields that are not named according to names of the joinable
tables.

Thanks.

Ivan Ukhov wrote:

Hello!

When we use has_many :through, is there a way to specify the name of
the class and the foreign key? This question pops up when the join
table has fields that are not named according to names of the joinable
tables.

Thanks.

Hey,

Say you have two entities A and B which need to have m->n relationship
in the ERM,
so ideally they would have a join table A_B_join_table with the foreign
keys from both A and B.

Now, say sometime later you decide that the join table should also
contain some additional data that would help your business logic. That's
the time when you should make the join table an active record model,say
C. But it should not break the relationship between A and B too.

That's when you can use A has_many B through C where C is also an active
record model. Result A -> C -> B similar to A -> B as earlier.

Also, in Rails 2.0, that uses RESTful architecture, it is emphasized to
use active record models instead of stand-alone join tables.

Check out the RailsConf Keynote by DHH. Make sure you have downloaded
the pdf before watching the video.
http://www.scribemedia.org/2006/07/09/dhh/