【发布时间】:2019-09-23 18:37:55
【问题描述】:
我有 questions、answers 和 photos models。我将paperclip 用于图像。
我无法使用以下代码将answer's image 添加到photos table。
q = Question.new(
title: p[:title],
post: p[:post]
)
p[:answers].each do |a|
q.answers.build(body: a[:body])
if a[:images]
a[:images].each do |e|
q.answers.photos.create(image: e) #this line gives the error
end
end
end
错误行q.answers.photos.create(image: e)
错误是:
undefined method `photos' for #<Answer::ActiveRecord_Associations_CollectionProxy:0x00007f9592208800>
我为我的模型创建了关联,例如:
class Answer < ApplicationRecord
belongs_to :question
has_many :photos
end
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
【问题讨论】:
-
尝试
create方法而不是build -
错误是由
create方法引起的,而不是build方法引起的。 -
你为什么用
p[:answer](例如)而不是p.answer?
标签: ruby-on-rails ruby ruby-on-rails-5 paperclip