I know this has been rehashed many times, but I don't get it.
I can’t find it documented to were I understand all the parts. I can
make this work using Rails database design conventions, but in this case
I am not able to do that.
I find examples, but the ones I find do not follow the conventions.
They also do not give enough information to understand what is going on.
In the model:
What is the “association”? Is it the field name minus the _id?
:foreign_key is the key in the other table.
:class_name is the name of the model of the other table.
------createtables.sql
CREATE TABLE admins(
id INTEGER PRIMARY KEY,
admin VARCHAR(32) NOT NULL,
);
CREATE TABLE machines(
id INTEGER PRIMARY KEY,
padmin_id REFERENCES admins(admin),
sadmin_id REFERENCES admins(admin)
)
-------models/machine.rb------------
class Machine < ActiveRecord::Base
belongs_to :padmin, :class_name => “admin”, :foreign_key => “id”
belongs_to :sadmin, :class_name => “admin”, :foreign_key => “id”
end
-------models/admin.rb--------------
class Admin < ActiveRecord::Base
has_many :machines, :foreign_key => ‘padmin_id’
has_many :machines, :foreign_key => ‘sadmin_id’
end
-------views/_list_stripes.rhtml-----
If it were a straight association machine.admin_id and admin.id, then
this works
Steve,
I think you understand my data. I was trying to avoid habtm. I
haven’t found a way to associate data with each join. We have primary
and secondary admins for each machine.
habtm does not deal with this:
administrators administrators_machines machines
id <---- administrator_id |–> id
admin machine_id – machine
[primary | secondary]
In the mean time I would like to figure out the correct syntax for
describing the models and listing the data with just belongs_to and
has_many. I would drop the secondary admin out of the model. But instead
of renameing things I would like to know how to do it without following
rails naming conventions.
The :through approach requires creating a new Model in ghe middle, say
‘adminship’,
so administrator has_many :adminships and has_many :machines :though
=> ‘adminships’
and machine has_many :adminships and has_many :administrators :through
=> ‘adminships’.
The adminships table, in addition to administrayor_id and machine_id
will have, say a priority column indicating primary or secondary
The Adminship model would belongs_to :machine and belongs_to
:administrator.