Relating two models through associated foreign keys with ruby on rails -
i'm having trouble setting relationships , queries. here simple explaination of want accomplish. have 3 models: drawings, changes, , revisions.
a drawing has many revisions
a change has many revisions
a change has many drawings through revisions
the drawings have fields primary key string: drawing_number
unique each drawing.
when create new change
, have nested form creates new revisions within change. have 1 of fields in new revision drawing_number
though foreign key drawing_id
. there way set enter drawing_number
in form, finds drawing_id
matches drawing_number
, , adds drawing_id
drawing_id column in revisions table.
in other words, want relate revisions drawings using associated field not foreign key.
for example: have drawing_id = 7 , drawing_number = a7114b1
i create new change has revision form nested in it. enter drawing_number a7114b1 form, revision model has drawing_id column, not drawing_number column. logic find drawing_id matches drawing_number, , place drawing_id revisions table.
assuming drawing_number
== drawing_id
if understood well, data correctly modeled, want alias attribute name on drawing
. can done #alias_attribute
:
class drawing < activerecord::base alias_attribute :drawing_number, :drawing_id end
now can use drawing_number
attribute way drawing_id
, like:
> drawing.where(drawing_id: 1) == drawing.where(drawing_number: 1) => true
assuming drawing_number
!= drawing_id
i'm assuming drawing
have attribute number
, revision
have attribute drawing_number
, both strings. need manually set foreign_key , primary_key of associations, following:
class drawing < activerecord::base has_many :revisions, foreign_key: :drawing_number, primary_key: :number end cass change < activerecord::base has_many :revisions end class revision < activerecord::base belongs_to :drawing, foreign_key: :drawing_number belongs_to :change end
Comments
Post a Comment