簡體   English   中英

保存前如何關聯Rails模型

[英]How to associate Rails models before one has saved

我正在嘗試構建博客應用,並且正在使用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的新手,所以任何指導都很棒。

您可能希望使用嵌套屬性將Blog與BlogImage同時保存。 您需要確保在每個模型(Blog和BlogImage)中正確設置了兩個模型之間的關聯。

在您的Blog模型中:

has_many :blog_images

在您的BlogImage模型中:

belongs_to :blog

在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

然后,當您保存Blog記錄時,嵌套在其中的所有BlogImage也會被關聯並保存。

此過程有很多部分,因此我將檢查一下這樣的教程: http : //tutorials.pluralsight.com/ruby-ruby-on-rails/ruby-on-rails-nested-attributes

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM