Rails - Paperclip ROLLBACK due to associations

133 Views Asked by At

I have 3 models. The question, answer and photo. I am using paperclip to save images. Questions and answers can have multiple images.

However, I get ROLLBACK when saving images for answer model. I don't get ROLLBACK when saving images for question model. I think I have a problem with model 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

My Controller :

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

Any thoughts?

1

There are 1 best solutions below

0
nathanvda On

Since rails 5 the belongs_to associations are by default required.

There are two possible solutions, either write

belongs_to :question, optional: true 

in your Photo model, or, as you are saving them through the nested association (a bit like a nested-form), you have to clearly indicate which association is the inverse of which.

So in your answer class, specify the inverse of the :photos association

 has_many :photos, inverse_of: :answer 

(to allow rails to correctly check that the belongs_to is set correctly)