【问题标题】:How to associate Rails models before one has saved如何在保存之前关联 Rails 模型
【发布时间】:2016-08-28 11:00:40
【问题描述】:

我正在尝试构建一个博客应用程序,并且正在使用 trix 文本编辑器和 CarrierWave。

Trip 编辑器允许您将图像拖到文本区域中,我已经设法通过使用以下代码将图像发布到他们自己的 BlogImages 控制器和模型来使图像上传工作:

#blog_images_controller.rb:

def create
  @image = BlogImage.create(image_params)
  @image.image = params[:image]

  respond_to do |format|
    if @image.save
      format.json { render :json => { url: @image.image.url } }
    end
  end
end

private
def image_params
  params.require(:image).permit(:image)
end

#blog_images.coffee:

(->
  host = undefined
  uploadAttachment = undefined
  document.addEventListener 'trix-attachment-add', (event) ->
    attachment = undefined
    attachment = event.attachment
    if attachment.file
      return uploadAttachment(attachment)
    return
  host = '/blog_images'

  uploadAttachment = (attachment) ->
    file = undefined
    form = undefined
    xhr = undefined
    file = attachment.file
    form = new FormData
    form.append 'Content-Type', file.type
    form.append 'image[image]', file
    xhr = new XMLHttpRequest
    xhr.open 'POST', host, true

    xhr.upload.onprogress = (event) ->
      progress = undefined
      progress = event.loaded / event.total * 100
      attachment.setUploadProgress progress

    xhr.onload = ->
      href = undefined
      url = undefined
      url = href = JSON.parse(@responseText).url
      attachment.setAttributes
        url: url
        href: href

    xhr.send form

  return
).call this

我现在的问题是我有一个已保存的 BlogImage,但他们需要关联的博客尚未创建,所以我无法设置此关联。我对 Rails 很陌生,所以任何指导都会很棒。

【问题讨论】:

  • 您应该看看嵌套表单:guides.rubyonrails.org/form_helpers.html#nested-forms 在保存主模型之前,您不应该创建关联模型。如果有人上传了几十张图片,然后选择不提交博客表单,会发生什么?您将留下垃圾图像模型。

标签: ruby-on-rails activerecord


【解决方案1】:

您可能希望在保存博客的同时使用嵌套属性保存其 BlogImages。您需要确保在每个模型(Blog 和 BlogImage)中正确设置了两个模型之间的关联。

在您的Blog 模型中:

has_many :blog_images

在您的BlogImage 模型中:

belongs_to :blog

在博客模型中添加accepts_nested_attributes_for :blog_images

更改 BlogController 的强参数以接受嵌套属性,如下所示:

def params
  params.require(:blog).permit(:title, :body, :published_on, blog_images_attributes: [:image_url, :another_image_attribute])
end

然后当您保存您的博客记录时,所有嵌套在其中的 BlogImages 都将被关联并保存。

这个过程有很多部分,所以我想看看这样的教程:http://tutorials.pluralsight.com/ruby-ruby-on-rails/ruby-on-rails-nested-attributes

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-01
    相关资源
    最近更新 更多