TimmyJ
TimmyJ

Reputation: 928

Rails custom foreign key not respected

The relevant database tables have these schemas:

sqlite> .schema structures
CREATE TABLE structures(
        struct_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        batch_id INTEGER,
        tag TEXT,
        input_tag TEXT,
        FOREIGN KEY (batch_id) REFERENCES batches(batch_id) DEFERRABLE INITIALLY DEFERRED);
sqlite> .schema residues
CREATE TABLE residues(
        struct_id INTEGER NOT NULL,
        resNum INTEGER NOT NULL,
        name3 TEXT NOT NULL,
        res_type TEXT NOT NULL,
        FOREIGN KEY (struct_id) REFERENCES structures(struct_id) DEFERRABLE INITIALLY DEFERRED,
        PRIMARY KEY (struct_id, resNum));

I have the following models:

class Structure < ActiveRecord::Base
    set_table_name "structures"
    self.primary_key = "struct_id"

    attr_accessible :struct_id, :batch_id, :input_tag

    has_many :residues
end

class Residue < ActiveRecord::Base
  self.primary_keys :struct_id, :resnum
  belongs_to :structure, :foreign_key => 'struct_id'
  attr_accessible :name3, :res_type, :resnum
end

In the structures show I have:

<h2>Residues</h2>
<% @structure.residues.each do |residue| %>
  <p>
    <b>Residue number:</b>
    <%= residue.resnum %>
  </p>

  <p>
    <b>Residue type:</b>
    <%= residue.res_type %>
  </p>
<% end %>

However, when I try to show a structure I get the following error:

SQLite3::SQLException: no such column: residues.structure_id

Why is structure_id being looked for in the database and not struct_id? It seems my foreign key is not being respected.

Upvotes: 1

Views: 220

Answers (1)

Frederick Cheung
Frederick Cheung

Reputation: 84182

You need to specify the foreign key on both sides of the relationship ( the has_many and the belongs_to)

Upvotes: 2

Related Questions