所以我有很多桌子。我需要获取所有没有链接的image_container的商品。我认为最好的方法是加入一个联接,这只会给我很多没有图像容器的东西。Join
Rails的默认设置与此完全相反。找到很多没有图像的最佳途径是什么?
@lots = @event.lots.order("#{sort_column} #{sort_direction}").page params[:page]
@lots = @lots.joins(:image_containers)
拿到没有抵押品的最好方法是image_container
什么?
Image_container是一个多态对象。因此,Image_container的imageable_type为“ Lot”,而imageable_id是批次的ID。
image_container模型:
belongs_to :imageable, :polymorphic => true
belongs_to :image, :inverse_of => :image_containers
事件模型:
has_many :image_containers, :as => :imageable, :inverse_of => :imageable, :dependent => :destroy
has_many :images, :through => :image_containers
批次模型:
has_many :image_containers, :as => :imageable, :inverse_of => :imageable, :dependent => :destroy
has_many :images, :through => :image_containers
您应该能够找到将image_container_id设置为的批次nil
:
@lots = @lots.joins("LEFT OUTER JOIN image_containers ON image_containers.imageable_id = lots.id AND image_containers.imageable_type = 'Lot' WHERE image_containers.id IS NULL")
希望这行得通,我自己对联接查询不是很熟悉。您可以通过添加.map{|lot| lot.image_containers.count}
到查询的末尾以检查返回的数组仅包含零来测试此方法是否有效。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句