Rails Polymorphic Association with multiple associations on the same model

后端 未结 10 1895
无人及你
无人及你 2020-11-28 03:01

My question is essentially the same as this one: Polymorphic Association with multiple associations on the same model

However, the proposed/accepted solution does no

10条回答
  •  爱一瞬间的悲伤
    2020-11-28 03:43

    Future reference for people checking this post

    This can be achieved using the following code...

    Rails 3:

    has_one :banner_image, conditions: { attachable_type: 'ThemeBannerAttachment' }, class_name: 'Attachment', foreign_key: 'attachable_id', dependent: :destroy
    

    Rails 4:

    has_one :banner_image, -> { where attachable_type: 'ThemeBannerAttachment'}, class_name: 'Attachment', dependent: :destroy
    

    Not sure why, but in Rails 3, you need to supply a foreign_key value alongside the conditions and class_name. Do not use 'as: :attachable' as this will automatically use the calling class name when setting the polymorphic type.

    The above applies to has_many too.

提交回复
热议问题