2017-04-25 54 views
-1

我有三個模型的照片,文章和評論。在照片中有一個多態關聯的attachable_id和attachable_type列。我想分別爲post和comments分配attachable_type值1,2。疑惑在多形軌道

我加入以下代碼

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 

但是,當我試圖讓美國郵政照片的數量NG

self.photos.count 

生成的查詢是

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

我不知道該怎麼photosattachable_type = 0添加到查詢中。請幫我避免查詢

回答

0

attachable_type應該是string而不是integer

如果您定義attachable_type爲1時,它屬於post,那麼您不必使用polymorphic,您只需定製它。

polymorphic的用法是錯誤的,attachable_type應該是the model's class name

例如

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> 

昌話對這

Post.rb

has_many :photos, as: :attachable 

Comment.rb

has_many :photos, as: :attachable 

並創建照片以這種方式

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

它會自動填寫attachable_typeattachable_id領域。

如果您確實希望該類型爲integer字段,請檢查此參考文獻,Polymorphic Assocations using Integer ID type fields。我的意見是,那麼你就不需要使用polymorphic,只需編寫一些自定義的方法,這很簡單。

+0

我們可以使用attachable_type作爲微小的int而不是字符串。我想優化列的大小 – CR7

+0

檢查此https://github.com/doliveirakn/polymorphic_integer_type,但我以前沒有使用它。如果你想要它是微小的int,那麼你需要編寫自定義代碼。因爲它不支持正式 –