views:

252

answers:

2

Trying to do a select field for an admin interface.

What I have is not a traditional many-to-many relationship, but I imagine the principles are the same. I have an "Event" model and an "EventRelation" model...every Event can have many sub-events, and one primary event...so EventRelation has primary_event_id and sub_event_id fields.

How would I make a select field that would allow me to specify a primary_event for any given Event?

The relevant model code:

class Event 'primary_event_id', :class_name=>'EventRelation'
  has_one :primary_event_relation, :foreign_key=>'sub_event_id', :class_name=>'EventRelation'


  has_one :primary_event, :through=>:primary_event_relation,  :foreign_key=>"primary_event_id"
  has_many :sub_events, :through=>:sub_event_relations, :foreign_key=>"sub_event_id"


end


class EventRelation 'Event', :foreign_key=>"primary_event_id"
  belongs_to :sub_event, :class_name=>'Event', :foreign_key=>"sub_event_id"

end


+1  A: 

I would use a plugin like Formtastic to accomplish this because it has support for various forms of ActiveRecord associations built into a solid alternative form handler. Just make sure you do an appropriate query with the most efficient join or include options for you model so that your view doesn't cause unnecessary database queries as it works through the associations.

James Thompson
A: 

As James says, Formtastic is a great way to go for this. And there are two great railscasts on how to use it.

Robert