sabrams
sabrams

Reputation: 1128

Relating two models through associated foreign keys with ruby on rails

I'm having trouble setting up my relationships and queries. Here is a simple explaination of what I want to accomplish. Say I have three models: Drawings, Changes, and Revisions.

A Drawing has many Revisions

A Change has many Revisions

A Change has many drawings through revisions

The Drawings have fields for primary key as well as a string: drawing_number that is unique to each Drawing.

When I create a new Change, I have a nested form that creates new Revisions within the Change. I would like to have one of the fields in the new Revision be the drawing_number even though the foreign key is the drawing_id. Is there a way to set it up so that I enter the drawing_number in the form, it then finds the drawing_id that matches that drawing_number, and adds that drawing_id into the drawing_id column in the Revisions table.

In other words, I want to relate the Revisions to the Drawings using an associated field that is not the foreign key.

For example: I have drawing_id = 7 and drawing_number = A7114B1

I create a new Change which has a Revision form nested in it. I enter drawing_number A7114B1 into the form, but the Revision model only has a drawing_id column, not a drawing_number column. I would like the logic to find the drawing_id that matches the drawing_number, and place the drawing_id into the Revisions table.

Upvotes: 0

Views: 209

Answers (1)

fotanus
fotanus

Reputation: 20116

Assuming drawing_number == drawing_id

If I understood well, your data is already correctly modeled, but you want an alias to your attribute name on Drawing. This can be done with #alias_attribute:

class Drawing < ActiveRecord::Base
  alias_attribute :drawing_number, :drawing_id
end

Now you can use drawing_number as an attribute exactly the way you would do with drawing_id, like:

> Drawing.where(drawing_id: 1) == Drawing.where(drawing_number: 1)
 => true

Assuming drawing_number != drawing_id

I'm assuming that Drawing have the attribute number and Revision have the attribute drawing_number, both as strings. You need to manually set foreign_key and primary_key of the associations, like the 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

Upvotes: 1

Related Questions