0

레일스 앱에는 두 개의 모델이 있습니다 : ListingListingPhoto. 내 모델에서 Listing 중첩 된 ListingPhoto을 제거하는 범위를 설정하려고합니다. 이것들은 외부 API에서 가져 오므로 이러한 절약을 제어하는 ​​쉬운 방법이 없습니다. Nested_attributes가 비어있는 경우 레일스 모델의 레코드를 숨기기

Listing

은 다음과 같습니다
class Listing < ActiveRecord::Base 

    acts_as_taggable_on :listing_types 

    has_many :listing_photos 
    accepts_nested_attributes_for :listing_photos, allow_destroy: true 

    private 

end 

ListingPhoto

은 다음과 같습니다

class ListingPhoto < ActiveRecord::Base 
    belongs_to :listing 
    validates :listing, presence: true 
    mount_uploader :photo, PhotoUploader 
end 

내가 빈 사진 세트가 보여주는 목록을 중지 내 Listing 모델에 추가 할 필요가?

+0

여기를보세요 : http://stackoverflow.com/questions/9613717/rails -find-record-with-zero-has-many-records-'with_photo' 범위를 추가하는 방법에 관한 것. 그런 다음 컨트롤러에서 표시 할 목록을 준비 할 때'List.all' 대신'List.with_photo'를 사용하십시오. – moonfly

답변

2

당신은 목록 모델에서 정적 메서드를 추가 할 수 있습니다

def self.with_photos 
    includes(:listing_photos).where.not(:listing_photos => {:listing_id => nil}) 
end 

및 그럼 그냥 쉽게 전화 :

Listing.with_photos 
관련 문제