views:

51

answers:

1

Hi All,

Ok, I've got a bit of an odd situation (as if none of my others were...). Basically I have a setup where there are 4 entities:

Sites -> Buildings -> Meters -> Values

I then have a fifth entity (Charts) that creates reports on the Values. I have a request to allow for Charts to be visually associated with any of those items in order to accommodate end users. Basically each chart can only be associated with any one entity at a time. Is there a quality "ACTS_AS" or something wild and crazy that will intuitively allow me to associate Charts with any and all entities without adding a table for each new association?

Best.

A: 

Perhaps you want polymorphic associations.

class Chart < ActiveRecord::Base
  # charts table has a chartable_id and a chartable_type column. Type is the 
  # class name of the associated chartable: Site, Building, etc.
  belongs_to :chartable, :polymorphic => true
end

class Site < ActiveRecord::Base
  has_one :chart, :as => :chartable
end

class Building < ActiveRecord::Base
  has_one :chart, :as => :chartable
end

# ...
Sarah Mei
Very nice. I'm having a bit of trouble wrapping my head around what the interface might look like. Drop boxes? Check boxes? *scratches head*
humble_coder
Ok, I've watched "Railscastcasts Episode 154" regarding Polymorphism and it definitely covers what I need. However, it misses one thing -- basically, it assumes that the person will be adding a new item via a form. However, I want to remotely submit via javascript and ajaxily (yup that's surely a word somewhere) display it in place. Any suggestions as to how to go about this while still keeping all the pertinent code in the CHART controller only?
humble_coder
...also, I'm getting UnknownAction errors when I try to do something like "Sites/1/charts". I've set my routes properly (per the railscast), but something is still broken. Any ideas?
humble_coder
Hmm, for the last issue, try doing a rake routes to see if they look correct.
Sarah Mei
Is doing it ajaxily that much different from submitting a form? You create the request by hand in Javascript, include the chartable_id and the chartable_type, then submit it to the create action. Or am I missing something?
Sarah Mei