Search code examples
ruby-on-railsruby-on-rails-3activerecordactivemodelhas-one

ActiveRecord relations: Can A has_many Bs AND A has_one B at same time?


I have a situation that I'm not sure how to handle in Rails:

Event has_many :photos and Photo belongs_to :event

simple enough

But, Event also needs to reference a single "key" photo.

Thought about adding:

Event has_one :key_photo, :foreign_key => "photo_id"

But will this work given has_many above? If so, how to handle the inverse in Photo model which already says Photo belongs_to :event?

I could add a boolean column to Photo that is true for only one row (the 'key' photo) but that seems like a waste...if only of a 1 bit column.


Solution

  • I think the cleanest implementation is having an extra FK in events for :key_photo.

    # events.rb
    belongs_to :key_photo, :class_name => 'Photo'