如何在保存之前关联Rails模型

时间:2016-08-28 11:00:41

标签: ruby-on-rails activerecord

我正在尝试构建一个博客应用程序,我正在使用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很陌生,所以任何指导都会很棒。

1 个答案:

答案 0 :(得分: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