我的产品索引返回所有产品,但我只想要有照片的产品。
控制器:
@products = Product.all.includes(:photos)
型号:
class Product < ActiveRecord::Base
has_many :photos
accepts_nested_attributes_for :photos, allow_destroy: true
end
class Photo < ActiveRecord::Base
has_attached_file :image
belongs_to :product
end
模式:
create_table "photos", force: true do |t|
t.integer "product_id"
t.string "image_file_name"
t.string "image_content_type"
t.integer "image_file_size"
t.integer "user_id"
end
add_index "photos", ["product_id"], name: "index_photos_on_product_id", using: :btree
add_index "photos", ["user_id"], name: "index_photos_on_user_id", using: :btree
create_table "products", force: true do |t|
t.string "name"
t.integer "price"
t.integer "user_id"
t.boolean "sold", default: false
end
您想获取至少具有一个products
的photo
?像这样使用内部联接:
@products = Product.
joins(:photos).
where(products: {sold: false}).
group("products.id")
这是最好的方法,IMO。
但是(只是为了向您展示可能的结果,您也可以获取在products
表中具有ID的photos
。
product_ids = Photo.pluck("DISTINCT product_id")
@products = Product.where(id: product_ids, sold: false)
也许这可能有效。 .includes允许在其上调用位置。
Product.all.includes(:photos).where("image != ?", nil)
如何简单:
@products = Product.include(:photos).select{ |prod| prod.photo.present? }