Previously I discussed getting my feet wet with has_many_polymorphs. In that article I promised a follow-up dealing with checkboxes in a polymorphic world. As I started keying the article, I ran into a much better description of the overall issue by Dylan Fareed (I presume) at I Am Still Alive. Take a look at his has_many_polymorphs overview.

Reading Fareed’s post, the key bit of code he developed is the abstract_id_assignement method. See, when you’re working with a typical has_and_belongs_to_many Rails relationship, the collection objects get some assignment methods for free. So given:

class People < ActiveRecord::Base
  has_and_belongs_to_many :foibles
end

You will get a foible_ids=(id_list) method for free. Not so in the has_many_polymorphs world. A similar topic was discussed in the Rails Forum. Fareed provides a nice solution to that issue. Once the code is in place, you can pretty much DRY up your arrays of checkboxes as described by Ryan Bates’s Railscast.

Oct 08, 2007 · Subscribe · Archive · Projects · Twitter · GitHub · Flickr