【问题标题】:Rails: find where nested attributeRails:查找嵌套属性
【发布时间】:2015-01-28 09:02:13
【问题描述】:

我的产品索引返回所有产品,但我只想要那些有照片的产品。

控制器:

@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

【问题讨论】:

    标签: ruby-on-rails-4 paperclip


    【解决方案1】:

    您想获取至少有一个photoproducts?像这样使用内部连接:

    @products = Product.
                joins(:photos).
                where(products: {sold: false}).
                group("products.id")
    

    这是最好的方法,IMO。

    但是(只是为了向您展示什么是可能的)您也可以获取在 photos 表中具有 ID 的 products

    product_ids = Photo.pluck("DISTINCT product_id")
    @products = Product.where(id: product_ids, sold: false)
    

    【讨论】:

    • 固体是指已售出?它是在产品型号而不是照片上出售的
    • 我收到此错误 Product Load (1.3ms) SELECT "products".* FROM "products" INNER JOIN "photos" ON "photos"."product_id" = "products"."id" WHERE "product"."sold" = 'f' GROUP BY photos.id PG::UndefinedTable: ERROR: missing FROM-clause entry for table "product" LINE 1: ... ON "photos"."product_id" = "products "."id" WHERE "product".... ^ : SELECT "products".* FROM "products" INNER JOIN "photos" ON "photos"."product_id" = "products"."id" WHERE "product" ."sold" = 'f' GROUP BY photos.id
    • 查看sold 条件。 product.sold 是错误的。我得出结论,您的代码中有错字。在您的where 条件下,您输入的是product: {sold: false},但它应该是products
    【解决方案2】:

    也许这可行。 .includes 允许在其上调用 where。

    Product.all.includes(:photos).where("image != ?", nil)
    

    【讨论】:

      【解决方案3】:

      来个简单的:

      @products = Product.include(:photos).select{ |prod| prod.photo.present? }
      

      【讨论】:

        猜你喜欢
        • 2011-02-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多