简体   繁体   English

如果nested_attributes为空,则在Rails模型中隐藏记录

[英]Hide record in Rails model if nested_attributes are empty

I have two models in my Rails app: Listing and ListingPhoto . 我的Rails应用程序中有两个模型: ListingListingPhoto I want to set some kind of scope on my model that removes Listing s that have no nested ListingPhoto s. 我想在模型上设置某种范围,以删除没有嵌套ListingPhotoListing These are being pulled in from an external API, so I have no easy way to control these saving. 这些是从外部API获取的,所以我没有简单的方法来控制这些保存。

Listing looks like this: 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 looks like this: ListingPhoto看起来像这样:

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

What would I need to add to my Listing model to stop listings with empty photo sets showing up? 要停止显示空白照片集的列表,我需要向Listing模型添加什么?

you can add static method in Listing model: 您可以在清单模型中添加静态方法:

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

and then just easily call: 然后只需调用:

Listing.with_photos

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM