-1

I have three models photo, post and comments. In photo there is a polymorphic association attachable_id and attachable_type column. I want to assign attachable_type value 1,2 for post and comments respectively.

I have added following code

Photo.rb

 belongs_to :attachable, polymorphic: true

Post.rb

has_many  :photos, -> { where(attachable_type: 1) }, as: :attachable, class_name: "Photo", dependent: :destroy

Comment.rb

 has_many  :photos, -> { where(attachable_type: 2) }, as: :attachable, class_name: "Photo", dependent: :destroy

But when I try to get the count of photos of a post using

self.photos.count

The query generated is

SELECT COUNT(*) FROM `photos` WHERE `photos`.`attachable_id` = 853 AND `photos`.`attachable_type` = 0 AND `photos`.`attachable_type` = 1

I don't know how photos.attachable_type = 0 added to the query. Please help me to avoid this from the query

CR7
  • 680
  • 2
  • 8
  • 24

1 Answers1

0

The attachable_type should be string, not integer.

If you define when attachable_type is 1, it belongs to post, then there's no need to use polymorphic, you have just custom it.

The usage for the polymorphic is wrong, attachable_type should be the model's class name.

for example

2.3.1 :001 > Notification.last
=> #<Notification id: 3733, notify_attachable_id: 489, 
notify_attachable_type: "Demander", created_at: "2017-04-10 
08:36:46", updated_at: "2017-04-10 08:36:46", already_read: false> 

Chang it to this

Post.rb

has_many :photos, as: :attachable

Comment.rb

has_many :photos, as: :attachable

and create the photos in this way

post.photos.create(image_url: 'http://xx.jpg')

it will auto fill attachable_type and attachable_id fields.

If you really want the type to be integer field, please check this refer, Polymorphic Assocations using Integer ID type fields. And my opinion is that then you just have no need to use polymorphic, just write some custom methods, it's simple.

Community
  • 1
  • 1
  • can we use attachable_type as tiny int instead of string. I want to optimize the size of the column – CR7 Apr 25 '17 at 05:49
  • check this https://github.com/doliveirakn/polymorphic_integer_type, but i haven't use it before. if you want it to be tiny int, then you need write custom code. because it doesn't support officially – seaify - Freelancer Apr 25 '17 at 05:53