1

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.

Meltemi
  • 37,979
  • 50
  • 195
  • 293

2 Answers2

0

For what it's worth, I would add/use the one bit column. It makes your code more expressive and shows the intent of your code better. Relying on quirks like "oh, it has_one AND has_many" is going to confuse other developers, such as yourself, in the future.

You're writing for other developers first, not the compiler or the database. Come back after the fact and make it more beautiful/elegant, with profiling. The odds that this one bit are going to cause record storage problems are minimal, at best.

jcolebrand
  • 15,889
  • 12
  • 75
  • 121
0

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

# events.rb
belongs_to :key_photo, :class_name => 'Photo'
cmpolis
  • 3,051
  • 21
  • 19
  • So, if I do this do I need to do the inverse somehow in `photo.rb` - which, remember, already has `belongs_to :post`? I'm not that familiar with what `ActiveRecord` & `ActivRelation` do under the hood so don't want to create a confusing conflict. – Meltemi Aug 26 '11 at 16:12
  • I just updated my code - should be 'belongs_to' since events keep the foreign key... You don't need to add anything to photo.rb; you just have to add key_photo_id to your events table. Then just use `event.key_photo` It doesn't really matter that there is already an association between photos and events - you can have as many as you need, as long as they use different foreign keys. – cmpolis Aug 26 '11 at 16:44