has_many belongs_to与外键关联

时间:2014-05-29 21:17:53

标签: ruby-on-rails ruby-on-rails-4 foreign-keys associations

假设您有两个模型VenuePhoto。每个Venue可以有多个Photos,但它只能有一个 FeaturedPhoto。每个Photo可以属于多个Venues,也可以是多个场地的FeaturedPhoto

我已经设置了一般的has_and_belongs_to_many关系,并通过这些模型的连接表进行处理:

class Photo < ActiveRecord::Base
  mount_uploader :image, PhotoUploader
  has_and_belongs_to_many :venues
end

class Venue < ActiveRecord::Base
  has_and_belongs_to_many :photos
end

要添加FeaturedPhoto,我似乎需要在Venue模型中添加名为featured_photo_id的列,然后在两者之间设置has_many,belongs_to关联。但我不知道在哪里添加foreign_key信息。这是对的吗?

class Photo < ActiveRecord::Base
  mount_uploader :image, PhotoUploader
  has_and_belongs_to_many :venues
  has_many :venues
end

class Venue < ActiveRecord::Base
  has_and_belongs_to_many :photos
  belongs_to :photo, foreign_key: "featured_photo_id", class_name: "Photo"
end

或者我必须向两个模型添加foreign_key信息吗?

2 个答案:

答案 0 :(得分:1)

如果为中间表PhotosVenue添加模型并在此中间表中添加布尔列is_featured,则可以实现此目的。

我创建了一个演示应用,可以完全按照您的要求进行操作。请检查此github repo

希望这会有所帮助:)

答案 1 :(得分:0)

has_many :through

我同意SiriusROR - 您需要使用has_many :through模型,并使用名为featured的额外布尔属性:

#app/models/photo.rb
Class Photo < ActiveRecord::Base
   has_many :photo_venues
   has_many :venues, through: :venue_photos
end

#app/models/venue.rb
Class Venue < ActiveRecord::Base
   has_many :photo_venues
   has_many :photos, through: :venue_photos do
       def featured
           find_by featured: true
       end
   end
end

#app/models/photo_venue.rb
Class VenuePhoto < ActiveRecord::Base
   belongs_to :photo
   belongs_to :venue
end

-

:through模型的架构应该设置如下:

#photo_venues
id | photo_id | venue_id | featured | created_at | updated_at

-

这将允许您致电:

@venue.photos.featured # -> should bring back the single ActiveRecord object for the first featured photo in the collection