2015-01-28 3 views
1

내 제품 색인은 모든 제품을 반환하지만 사진이있는 제품 만 원합니다.레일 : 중첩 된 속성을 찾으십시오

컨트롤러 :

@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 

스키마 : 당신은 적어도 하나의 photoproducts을 인출 할

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 

답변

1

? 다음과 같이 내부 조인을 사용하십시오.

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

이것이 가장 좋은 방법입니다.

(가능한 것이 무엇인지 보여주기 위해) photos 테이블에 ID가있는 products을 가져올 수도 있습니다.

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

당신은 판매 의미? 제품 모델에서 판매 됨 –

+0

이 오류는 제품로드 (1.3ms) "제품"을 선택하십시오. * FROM "products"INNER JOIN "photos"사진 "ON" "product_id"= "products". "id "WHERE"product "."sold "= 'f'GROUP BY photos.id PG :: UndefinedTable : 오류 :"product "테이블의 FROM 절 항목이 누락되었습니다. LINE 1 : ..."photos "."product_id "제품". "id" "제품".... .... ^ : "제품"에서 "제품"INNER JOIN "사진"ON "사진". "product_id"= "제품". " id "WHERE"product "."sold "= 'f'GROUP BY photos.id –

+0

'판매 된'조건을보십시오. 'product.sold'는 잘못되었습니다. 나는 당신이 당신의 코드에 오타가 있다고 결론을 내린다. 'where :'조건을 입력 할 때'product : {sold : false} '를 입력했는데'products'이어야합니다. – Humza

0

아마도이 문제가 발생할 수 있습니다. .includes를 사용하면 어디에서 호출 할 수 있습니다.

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

이 작동하지 않습니다. –

0

간단한에 대해 어떻게 : 고체으로

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

이 오류가 발생했습니다 : https://gist.github.com/alaingoldman/39d5e4c8fa288b098f0b –