Discussions of multi-model forms and nested models in Rails has been revived recently, with various changes appearing in Edge Rails, plugins like attribute_fu getting a lot of attention, and the release of ActivePresenter. It looks like when the dust settles we’ll have a nice new set of ways to simplify our code.
One thing I frequently find myself doing is associating multiple images with a given model. My news story might have a banner image, and a series of other attachments, which I could specify with:
class Story < ActiveRecord::Base
belongs_to :banner_image
has_many :story_attachments
end
class BannerImage < ActiveRecord::Base
has_attachment # I'm using attachment_fu
end
class StoryAttachment < ActiveRecord::Base
has_attachment # I'm using attachment_fu
end
(or I could use has_one in place of belongs_to there, your tastes/requirements may vary)
What quickly becomes a pain is assigning the images to the models, and having rejected fat controllers I often end up writing accessors on my models to manage that for me:
class Story data)
end
end
def valid_file?
# etc.
end
end
That quickly gets dull, so I’ve wrapped it up in a plugin I’m calling image_associations. With that I can write:
class Story < ActiveRecord::Base
belongs_to_image :banner_image
has_many_images :story_attachments
end
and get the accessors for free.
It may only be of use to me, and it’s pretty crude (there’s no support for deleting attachments, for example) but it’s been working nicely and has DRYed up my code in a satisfying way, so I thought I’d throw it out there. You can find it over on github.
(I’m not promising to keep supporting it, but it is used in an active project so chances are bug fixes will make it in. And of course, anyone is welcome to branch the project and twist it in their own ways)