Announcing image_associations

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)

Tags: , , ,

5 comments

  1. I wouldn’t mind adding this to attachment_fu with method names like belongs_to_attachment and has_many_attachments… This was actually how attachment_fu worked originally.

  2. That’d be great, rick.

    I’m headed out of town tomorrow but could look at what it’d take to turn my plugin into a patch some time next week?

  3. Have you looked at the rewrite branch of attachment_fu at all? I’ve been wanting to make it master and push the current master to a legacy branch. It’s a *huge* change from the current attachment_fu though. But IMO it’s a much-needed simplification and reorg of the code.

  4. I haven’t had a chance, but will definitely check it out and explore next week.

  5. […] Thoughtbot have released a suite of plugins over the past few months that are enlivening the fields of Ruby on Rails file attachments (paperclip) and authentication (clearance), long dominated by Rick Olson’s attachment_fu and restful_authentication. You can see some previous posts about attachment_fu here and here. […]