新手问题 accepts_nested_attributes_for polymorphic 遇到 ajax

kingwkb · 2013年06月09日 · 最后由 Lucia_ca 回复于 2018年06月25日 · 2622 次阅读
class topic

  has_many :pictures, as: :imageable

  accepts_nested_attributes_for :pictures
end

class picture
  belongs_to :imageable, polymorphic: true
  attr_accessible :image, :description
  mount_uploader :image, ImageUpload
end

class PictureController 
  def create
    @picture = Picture.new params[:picture]
    @picture.save
  end
end

class TopicController
  def create
    @topic = Topic.new params[:topic]
    @topic.save
  end
end

Picture 是通过 ajax 上传的,上传之后 imageable_type 和 imageable_id 都是空的,通过 js 把这个 picture 的表单写到 topic 的 form 中,提交保存 topic 时候遇到错误

SELECT `pictures`.* FROM `pictures` WHERE `pictures`.`imageable_id` IS NULL AND `pictures`.`imageable_type` = 'Topic' AND `pictures`.`id` IN (12)

找不到 pictures.id = 12 的,因为查询语句多了个 imageable_type 的条件

这个问题好什么好的解决办法吗?

ps: 我知道可以在保存 Pictures 的时候把 imageable_type 一起保存,有没有更 ruby 的解决办法?

我也遇到了同样的问题,请问最后是如何解决的?

需要 登录 后方可回复, 如果你还没有账号请 注册新账号