Rails has_one关系外键是拥有模型吗?

时间:2015-05-14 14:56:09

标签: ruby-on-rails rails-activerecord

我有PhotoPhotoset型号:

Photoset应该有多个photos和一个primary_photoPhoto应属于许多Photosets,可以是许多照片的primary_photo

但是我对如何设置primary_photo关系感到难过。我设想在primary_photo_id中添加photosets,但我无法弄清楚如何定义has_one以便在所属方面定义列(Photoset)。

我尝试通过以下方式实现此目的:

  • 添加photo_photosets联接表。
  • primary_photo_id列添加到photosets

我在模特中建立了关系:

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

1 个答案:

答案 0 :(得分:3)

    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