I have a question about a has_many + belongs_to relationship and how
ActiveRecord works. Consider two tables and related model classes:
create_table :projects do |t|
t.column :description, :text
t.column :fm_project_id, :integer
end
create_table :fm_project_divs do |t|
t.column :project_id, :integer
t.column :cat_id, :integer
t.column :name, :string
end
The projects table (class Project) has the rails standard ‘id’ primary
key.
The fm_project_divs table (class FmProjectDiv) does NOT - it’s a legacy
table and it actually has a composite key (project_id + cat_id), but not
defined here.
Apparently there is a required add-on to rails to support composite
keys…
A Project has_many fm_project_divs, and it is associated to the
fm_project_divs table by fm_project_id (of Project) mapping to
project_id (of FmProjectDiv).
Here are the model classes:
class Project < ActiveRecord::Base
has_many :fm_project_divs, :class_name => “FmProjectDiv”,
foreign_key => “project_id”
end
class FmProjectDiv < ActiveRecord::Base
belongs_to :project, :class_name => “Project”,
:foreign_key => :fm_project_id
end
In experimenting with this, has_many on Project attempts to collect
fm_project_div records using ‘id’ (primary key) matching on
‘project_id’, which isn’t what I need.
I’m able to get around this by:
has_many :fm_project_divs,
:class_name => “FmProjectDiv”,
:finder_sql => ‘SELECT * FROM fm_project_divs WHERE project_id =
#{fm_project_id}’
Is this very basic relationship not possible (without using finder_sql)
be/c rails demands a primary key defined for FmProjectDiv? Would this
work as expected if the composite key add-on were used?
thanks,
bob