1

I have same problem as : Rails Polymorphic Association with multiple associations on the same model

But the solutions on this question aren't working for me. I have a picture model and an event model. Event has many pictures and one cover pic. Here are both the models.

class Picture < ActiveRecord::Base
  belongs_to :image, polymorphic: true
end


class Event < ActiveRecord::Base
  has_many :pictures, as: :image, :dependent => :destroy
  has_one :cover_picture, -> { where image_type: "CoverPicture"},
     class_name: Picture, foreign_key: :image_id,
     foreign_type: :image_type, dependent: :destroy
end

Issue here is that when I create a new picture and set it as cover_picture of an event, it doesn't set the image_type to "CoverPicture". When I try and save it after specifically setting the image_type to "CoverPicture", it errors out with "NameError: uninitialized constant CoverPicture"

Community
  • 1
  • 1
asingla
  • 81
  • 6

1 Answers1

2

image_type has a specific function in this polymorphic association... it identifies the associated model (just as image_id identifies the id).

You should not be changing image_type as that breaks the association.

Make a new boolean column in the picture model, say cover_picture, and you can do...

has_one :cover_picture, -> {where cover_picture: true} ...

The advantage of this is your cover picture is also included in your pictures association, but if you want that picture excluded from the has_many then you can apply a where clause to that as well...

has_many :pictures, -> {where.not cover_picture: true} ...
SteveTurczyn
  • 36,057
  • 6
  • 41
  • 53
  • All the answers on [link](http://stackoverflow.com/questions/2494452/rails-polymorphic-association-with-multiple-associations-on-the-same-model) suggest what I tried. Any thoughts why it might be working for them? – asingla Nov 30 '16 at 02:51
  • The top-rated answer on that link is exactly my answer. He suggests an ADDITIONAL, DIFFERENT field called `photo_type`, (I suggested a different field called `cover_picture`). He is NOT using the polymorphic fields which (in his case) are `attachable_type`and `attachable_id` so his `photo_type` field is a separate column and does not mess up his polymorphic associations. If you want to create a new field called `photo_type` that's fine, go ahead. But DON'T use `image_type` because your polymorphic fields are `image_type` and `image_id`. – SteveTurczyn Nov 30 '16 at 10:41