Laurens
Laurens

Reputation: 2088

ActiveRecord foreign key set to null

I am using Ruby 1.8.7 and Rails 2.3.8 and I have the following root resource:

class PointOfInterest < ActiveRecord::Base
  set_primary_key "Id"
  set_table_name  "POI"

  has_many :attributes, :foreign_key => 'POIId'
end

The point of interest can have several attributes:

class Attribute < ActiveRecord::Base
  set_primary_key "Id"
  set_table_name  "Attribute"

  belongs_to :point_of_interest, :foreign_key => 'POIId'

  has_one :multimedia, :foreign_key => 'Id', :primary_key => 'Value'
end

The attribute class may have media associated with it:

class Multimedia < ActiveRecord::Base
  set_primary_key "Id"
  set_table_name  "Multimedia"
end

I am trying to insert a point of interest in my database like so:

poi = PointOfInterest.new
attr = poi.attributes.new
attr.SomeAttribute = 1
attr.build_multimedia(:content => 'test')
poi.save

This is properly persisting both the root (PointOfInterest) and the Multimedia record. The Attribute, however, is not being properly persisted. While the foreign key to the point of interest is properly set (POIId), the foreign key to the Multimedia record remains null.

Any clue as to why this is very much appreciated!

Thanks!

Upvotes: 0

Views: 1289

Answers (1)

Chowlett
Chowlett

Reputation: 46675

Your relationship / foreign key are set at cross purposes.

If Attribute has_one Multimedia, then you need the Multimedia model to declare belongs_to :attribute, and the Multimedia table to contain a foreign key for Attribute.

I'm guessing that you can't change your database schema (otherwise, I'd have to ask why you're using non-Rails-standard table and key names); in which case you want to switch the sense of the relation. Make Attribute belongs_to :multimedia, and Multimedia has_one :attribute. Then the Multimedia FK in the Attribute table is pointing in the right direction.

Upvotes: 1

Related Questions