Stuart Fellowes wrote:
I haven’t gotten a good feel for the :source option. Reading through
the doc it seems to reference another model ?
It describes how to get at the other model in a many-to-many
relationship with weird fieldnames.
For a many-to-many “has_many :through” relationship, Rails assumes you
have a schema like the following (habtm wouldn’t have a Second.id):
First:
id
Second:
id
first_id
third_id
Third
id
and models like
class First < ActiveRecord::Base
has_many :thirds, :through => :seconds
end
class Second < ActiveRecord::Base
belongs_to :first
belongs_to :third
end
class Third < ActiveRecord::Base
has_many :firsts, :through => :seconds
end
This sets up a many-to-many relationship between First and Third. Now if
your Second schema was like this:
Second:
id
weird_first_id
weird_third_id
…then Rails’s assumption about what your fields will be called will be
wrong and you have to tell it, like this:
class First < ActiveRecord::Base
has_many :thirds, :through => :seconds,
:foreign_key => :weird_first_id, :source => :weird_third_id
end
class Second < ActiveRecord::Base
belongs_to :first, :foreign_key => :weird_first_id
belongs_to :third, :foreign_key => :weird_third_id
end
class Third < ActiveRecord::Base
has_many :firsts, :through => :seconds,
:foreign_key => :weird_third_id, :source => weird_first_id
end
I hope I got that all right.
has_many tell Rails that (or actually, tells Rails to set up accessor
methods based on the assumption that) there is another table out there
which references this model and has field which stores the id of a
record in this model. So has_many’s :foreign_key is talking about the
field in the other table.
belongs_to tells Rails that this model references a record in another
table, and that this model stores the id of a record in the other table.
So belongs_to’s :foreign_key is talking about the field in this table.
has_many :through tell Rails that this table is joined to another (far)
table by a middle table which has fields which store the ids of a record
in this table and a record in the far table. So has_many :through’s
:foreign_key talks about a field in the middle table referencing this
table, and has_many :through’s :source talks about a field in the middle
table referencing the far table.
:source is ONLY used for :through associations, so it doesn’t apply to
your Cdetail/Person relationship (which is one-to-many, not
many-to-many, which is what :through is primarily for).
Just saw your last post, will follow up.