我有三個模型的照片,文章和評論。在照片中有一個多態關聯的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
我不知道該怎麼photos
。 attachable_type
= 0添加到查詢中。請幫我避免查詢
我們可以使用attachable_type作爲微小的int而不是字符串。我想優化列的大小 – CR7
檢查此https://github.com/doliveirakn/polymorphic_integer_type,但我以前沒有使用它。如果你想要它是微小的int,那麼你需要編寫自定義代碼。因爲它不支持正式 –