ruby on rails - The has_many :through Association - Modification? -
i have read through basics of association app fits `has_many :through associations properly...but there 1 issue other question lacks.
i'd rather ask question keep question clear , clean.
in understanding of how has_many :through associations work whenever doctor has new patient, new appointment created or has created patient. while makes sense, my app dont 1 bit.
in case, whenever user 'likes' someone's posts, creates new post. dont want 1 bit. i'm trying understanding of rails association answer other question pertaining one. how prevent 'appointment' being automatically created? or make perfect sense, when new instance of patient
created , merged doctor.patients
, creates new appointment.
d = doctor.new p = patient.new = appointment.new # created or not foo = doctor.find(1) foo.patients << p # creates new appointment not want.
whenever there many-to-many relationship, instance:
- any single doctor can have multiple patients
- any single patient can have multiple doctors
the database needs third table. because can't put multiple values patient_id
column of doctor table, , can't add on columns (how know how many add, , searching nightmare!).
the solution create "join" table, table 2 columns—in case doctor_id
, patient_id
. if doctor "x" has patients "a", "b", , "c", can add 3 records join table. if patient "a" has 2 doctors, "x" , "y," can represent well:
example join table "doctors_patients"
doctor_id | patient_id x x b x c y
see how gets around problem? in example cited, appointment
table, although it's model, acts join table doctors , patients. there's no reason can't add additional columns such date, time, room number, etc. on join table.
example join table "appointments"
doctor_id | patient_id | date x 1/1/2016 x b 1/2/2016 x c 1/3/2016 y 1/4/2016
but if there's no need refer model representing join table, can use has_and_belongs_to_many
association (see rails guide). still need make join table in migration regardless, again, need in order represent many-to-many association, there's no reason have give name or represent model.
models:
class user < activerecord::base has_and_belongs_to_many :posts end class post < activerecord::base has_and_belongs_to_many :users end
migration:
class createusersandposts < activerecord::migration def change create_table :users |t| t.string :name t.timestamps null: false end create_table :posts |t| t.text :content t.timestamps null: false end # join table create_table :posts_users, id: false |t| # posts comes before users alphabetically t.belongs_to :posts, index: true t.belongs_to :users, index: true end end end
Comments
Post a Comment