Topic: One More Association-Related Question

I decided to add an Image model to my application - the idea being that I can store what limited RMagick code I need within that model, and easily reference which image is being displayed where.

However, I'm having some trouble with associating the images. I need a single image to be used by multiple objects, and I need those objects to be of potentially disparate classes. In other words, I need something like:

[code:ruby]class Image < ActiveRecord::Base
  has_many :subjects, :polymorphic => true[/code]

Which seems to work fine. But when I add the other end:

[code:ruby]class Tile < ActiveRecord::Base
  belongs_to :image, :as => :subject[/code]

I get the error that 'as' is an invalid tag. Am I going about this entirely the wrong way? I suppose I could simply have an action writing the image on the filesystem in a controller somewhere, and then reference it through the URL... But I want this to work!

Any help will bring the peace of Buddha to you and your descendants.

God is a storyteller.

Re: One More Association-Related Question

Polymorphic association is intended to be used the other way:

class Image < ActiveRecord::Base
  has_many :subjects, :as => :image
end

class Tile < ActiveRecord::Base
  belongs_to :image, :polymorphic => true
end


But obviously this isn't what you want, so polymorphic association won't work for you here. Instead you'll need to do this:

class Image < ActiveRecord::Base
  has_many :tiles
  has_many :articles # or whatever

  def subjects # will you even need to fetch all of the "subjects"?
    tiles + articles
  end
end

class Tile < ActiveRecord::Base
  belongs_to :image
end

class Article < ActiveRecord::Base
  belongs_to :image
end


If you want a many-to-many association (tile/article has_many images too) than we can do something with polymorphic association by adding a join model. If you want to go this route I can post a code sample.

Railscasts - Free Ruby on Rails Screencasts