-2

我有 3 个models。和。_ question_ 我正在使用图像。并且可以有。answerphotopaperclipsaveQuestionsanswersmultiple images

但是,我在为模型ROLLBACK保存图像时得到了。为模型保存图像时answer我没有得到。我觉得我有问题。ROLLBACKquestionmodel associations

#photo model
class Photo < ApplicationRecord
  belongs_to :question 
  belongs_to :answer

  has_attached_file :image :path => ":rails_root/public/img/:filename", validate_media_type: false
  do_not_validate_attachment_file_type :image
end

#answer model
class Answer < ApplicationRecord
 belongs_to :question
 has_many :photos
end

#question model
class Question < ApplicationRecord  
  has_many :answers
  has_many :photos
end

我的控制器:

p.answers.each do |a|
  new_answer = q.answers.create(body: a[:body])
  if a[:images]
    a[:images].each do |e|
      new_answer.photos.create(image: URI.parse('www.abc.com/'+e))
    end
  end
end

有什么想法吗?

4

1 回答 1

0

从 Rails 5belongs_to开始,默认情况下需要关联。

有两种可能的解决方案,要么写

belongs_to :question, optional: true 

在您的Photo模型中,或者,当您通过嵌套关联(有点像嵌套形式)保存它们时,您必须清楚地指出哪个关联与哪个相反。

:photos因此,在您的答案类中,指定关联的倒数

 has_many :photos, inverse_of: :answer 

(以允许 rails 正确检查 belongs_to 设置是否正确)

于 2019-09-24T17:17:34.420 回答