Rails嵌套表格& has_many:通过模型,在父验证之前不要保存嵌套属性

时间:2013-11-16 00:10:54

标签: ruby-on-rails ruby-on-rails-4

我对rails很新,并且一直试图为has_many:through关系设置嵌套表单。目前,我有这些模型 -

class Building < ActiveRecord::Base
  has_many :building_photo_matchings
  has_many :photos, through: :building_photo_matchings
  accepts_nested_attributes_for :photos, reject_if: :all_blank
  validates :name, presence: true, length: {in: 1..100}, uniqueness: true
end

class BuildingPhotoMatching < ActiveRecord::Base
  belongs_to :building
  belongs_to :photo
end


class Photo < ActiveRecord::Base
  has_many :building_photo_matchings
  has_many :buildings, through: :building_photo_matchings
  belongs_to :user
  accepts_nested_attributes_for :buildings, reject_if: :all_blank
  mount_uploader :photo, PhotoUploader
end

嵌套表单的工作方式相反。我可以创建一个建筑物并上传它的许多照片。我可以上传照片并识别其中的建筑物。

但是出现了一个问题:当我创建一个建筑物并为其上传许多照片时,即使建筑物未经过验证,照片仍会保存。

现在我正在通过控制器处理这个问题,如果建筑物无效,则会销毁所有照片。我不认为这是一个很好的方法。有没有什么方法可以阻止嵌套属性保存,除非首先验证建筑物?

  def new
    @building = Building.new
    4.times {@building.photos.build}
  end

  def create
    @building = Building.new(building) 
    if @building.invalid?
      for @photo in @building.photos
        @building.destroy!
      end
    end
    if @building.save
      redirect_to buildings_path
    else
      render 'new'
    end
  end

1 个答案:

答案 0 :(得分:0)

您是否尝试过validates_associatedvalidates_presence_of

在控制器中执行此操作的更好方法是使用before_save回调,但模型验证是更好的整体方法。

相关问题