accepts_nested_attributes_for
我的代码:
# app/model/report.rb
class Report < ActiveRecord::Base
has_many :photos, class_name: Asset::Photo, dependent: :destroy
accepts_nested_attributes_for :photos
end
# app/model/asset/photo.rb
class Asset::Photo < ActiveRecord::Base
self.table_name = 'asset_photos'
belongs_to :report
validates :file, :report, presence: true
mount_uploader :file, Asset::Photo::FileUploader
end
> a = Report.new rating: 5, user: User.last,
photos_attributes: [{file: File.open(Rails.root+'spec/fixtures/test.png')}]
> a.save # false
> a.errors
=> #<ActiveModel::Errors:0xba758360
@base=#<Report id: nil, rating: 5, user_id: 18, created_at: nil, updated_at: nil>,
@messages={:"photos.report"=>["can't be blank"]}>
"photos.report"=>["can't be blank"]
?谢谢:)答案 0 :(得分:1)
当您保存report
时,它会尝试首先保存photos
。问题是还没有保存report
对象,因为它仍然只在内存中。解决方案是使用inverse_of
。
在尝试通过关联获取对象之前,inverse_of
选项告诉ActiveRecord
更聪明并查看内存。通过这样做,它在内存中找到未保存的报告,并将其识别为您要验证的报告。
通常,正如Rails doc指定的那样,它会尝试根据关联名称中的启发式来猜测反向关联。但是你使用class_name
的事实使得Rails无法猜测是否强迫你指定自己的inverse_of
。
尝试将您的belongs_to替换为:
belongs_to :report, inverse_of: :photos
你的has_many:
has_many :photos, class_name: Asset::Photo, dependent: :destroy, inverse_of: :report