max
max

Reputation: 102368

Rails has_one relationship where foreign key is on owning model?

I have a Photo and Photoset model:

A Photoset should have many photos and one primary_photo. A Photo should belong to many Photosets and can be the primary_photo of many photosets.

However I am stumped as how to setup the primary_photo relation. I was envisioning adding a primary_photo_id to photosets but I can't figure out how define the has_one so that the column is defined on the owning side (Photoset).

I tried to implement this by:

I setup up the relations in my models:

class Photo < ActiveRecord::Base
  has_and_belongs_to_many :photosets
  validates_uniqueness_of :flickr_uid
end

class Photoset < ActiveRecord::Base
  belongs_to :user
  validates_uniqueness_of :flickr_uid
  has_and_belongs_to_many :photos
  has_one :primary_photo, class_name: 'Photo' # !???
end

Upvotes: 2

Views: 253

Answers (1)

ShallmentMo
ShallmentMo

Reputation: 449

    class Photo < ActiveRecord::Base
      has_and_belongs_to_many :photosets
      validates_uniqueness_of :flickr_uid
    end

    class Photoset < ActiveRecord::Base
      belongs_to :user
      validates_uniqueness_of :flickr_uid
      has_and_belongs_to_many :photos
      belongs_to :primary_photo, class_name: 'Photo'
    end

Upvotes: 3

Related Questions