Alright, noob here, etc. etc.
Trying to figure out the has_many usage. If I understand correctly, when
you declare that a table/class has_many whatevers, the rails assumption
is that there will be a foreign key in the whatevers table pointing back
to the ‘id’ primary key in the first table. This doesn’t seem to be the
only way to have a ‘has_many’ relationship, and I can’t seem to get
override the rails assumptions for my tables. I have two tables,
‘properties’ and ‘jurisdiction_rates’.
class CreateProperties < ActiveRecord::Migration
def self.up
create_table :properties do |t|
t.column :address, :string
t.column :jurisdiction_id, :string
end
end
class CreateJurisdictionRates
def self.up
create_table :jurisdiction_rates do |t|
t.column :jurisdiction_id, :string
t.column :tax_rate, :string
t.column :type, :string
end
end
Rails of course sets up auto incrementing ‘id’ columns on both tables.
Now there are many properties in the same tax jurisdiction that will
have the same rates applied to them, so all properties in
‘jurisidiction_id’ = 999 have up to three tax ‘type’ (e.g. state, county
and local) associated with them. Clearly, I’d prefer to have the
‘jurisdiction_id’ in ‘properties’ join to
‘jurisdiction_rates.jurisdiction_id’ rather than a ‘properties_id’,
since if I did it the latter way, I’d have millions of records (three
tax rates entries for each property ‘id’, rather than 200 records for
each jurisdiction ‘id’). Using a habtm also seems like overkill. Am I
just not thinking about my table design intelligently? Or is there some
way to get rails to play with this structure? I’ve tried to use:
class Property < ActiveRecord::Base
has_many :jurisdiction_rates, :foreign_key => “jurisdiction_id”
end
class JurisdictionRates < ActiveRecord::Base
belongs_to :properties, :foreign_key => “jurisdiction_id”
end
This doesn’t seem to work at all. I can’t figure out how to tell rails
to use the ‘jurisdiction_id’ on both tables to do the join. Any
thoughts? Maybe I just need some sleep and my mistakes will be obvious.
jsma