HABTM question

While the habtm model for rails is very easy to use, some tables don’t
seem to fit easily into that structure. The problem is that the link is
(I believe) always done on the id column. One common table in a lot of
databases is a state codes table with one column for state code, another
for state name, and possibly others for different things about the
state. Other tables that have addresses typically link to the states
table by the 2 character post office code for the state.

Is there a way within rails to define this relationship? e.g. a habtm
setup on a column other than id. I’m sure there are other examples of a
need for this; the state code is probably just one of the more common
ones.

i think the convention would be to not hold any of the data about
states in the address table. instead the join table contains info about
the addresses table and states table. then rails knows what you want to
do when you tell it to use an habtm relationship.

is it possible you are describing a has-many relationship and not a
has-and-belongs-to-many relationship?

anyway, for a habtm relationship, i think the convention would be to
not hold any of the data about states in the address table. instead the
join table contains info about the addresses table and states table.
then rails knows what you want to do when you tell it to use an habtm
relationship.

lm wrote:

is it possible you are describing a has-many relationship and not a
has-and-belongs-to-many relationship?

Actually, the example I cited is a has-many. I notice that there is a
foreign-key parameter to the has-many helper. Can this be used to tell
rails that the linking column is the state code instead of the id?
Assuming the table name is states and the column name is statecode, what
would be the syntax for this?

if you’re dealing with a legacy system:

class State < ActiveRecord::Base
set_primary_key “statecode”
has and belongs_to_many :addresses, :foreign_key => “statecode”
end

class Address < ActiveRecord::Base
has_and_belongs_to_many :states, :association_foreign_key =>
“statecode”
end

where your states table is:

statecode (PK)
name

and your join table, addresses_states, is

statecode
address_id

if you are designing from scratch, just use an id column in the states
table and do away with all the extra work above.

the argument is that any column that carries a meaning, no matter if
it’s unique or not, should not be used as a primary key field. the id
column’s only purpose is to uniquely identify that row and should
carry no meaning/purpose beyond that.

Chris

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