1

我不知道如何在我的应用程序中自动保存连接表记录。我正在构建一个应用程序来让用户制作一本书。他们创建页面并上传图片库,然后将图片连接到页面。每本书都有一个封面,其中有一个封面图片。

我的目标只是能够设置书的封面图像文件名,并在保存书时保存子模型更改。(我已经缩小了示例范围,因此我们不处理实际附加的图像 - 这不是问题)。

class Book < ActiveRecord::Base
  has_many :pages, :dependent=>:destroy, :autosave=>true
  has_many :images, :dependent=>:destroy, :autosave=>true
  attr_accessible :title, :pages_attributes

  # we want to be able to set the cover page image filename for a book
  attr_accessor :cover_image_file_name

  before_validation do 
    # a book always has a cover page as page 0
    cover_page = pages.find_or_initialize_by_page_number(0)
    if @cover_image_file_name
      page_image = cover_page.page_images.find_or_initialize_by_image_type('cover')
      page_image.image = images.find_or_initialize_by_image_file_name(@cover_image_file_name)
    end
  end
end

class Image < ActiveRecord::Base
  belongs_to :book
  has_many :page_images,:dependent=>:destroy
  attr_accessible :image_file_name
end
class Page < ActiveRecord::Base
  belongs_to :book
  has_many :page_images, :dependent=>:destroy, :autosave=>true
  attr_accessible :page_number, :page_images_attributes
end
class PageImage < ActiveRecord::Base
  belongs_to :page
  belongs_to :image
  attr_accessible :image_type, :image
end

现在,当我执行以下代码来创建一本书并设置(或重置)其封面图像时,不会保存将新创建的图像连接到封面的 page_image 对象:

book = Book.new({ title: "Book Title" })
book.save!  # this correctly saves the book and its cover page

book.cover_image_file_name = 'my_cover_page.png'
book.save!  # the image gets created and saved, but not the page_image

我错过了什么?我认为它可能与https://github.com/rails/rails/pull/3610有关,但我使用的是 rails 3.2.9。

4

1 回答 1

1

当您尝试将图像分配给*belongs_to :image* 的page_image时,不会保存最后一个。因为此时图像(作为父对象)没有保存。

所以你只需要在 page_image 和 book 一起保存之前保存它。

class Book < ActiveRecord::Base
  has_many :pages, :dependent=>:destroy, :autosave=>true
  has_many :images, :dependent=>:destroy, :autosave=>true
  attr_accessible :title, :pages_attributes

  # we want to be able to set the cover page image filename for a book
  attr_accessor :cover_image_file_name

  before_validation do 
    # a book always has a cover page as page 0
    cover_page = pages.find_or_initialize_by_page_number(0)
    if @cover_image_file_name
      image = images.find_or_initialize_by_image_file_name(@cover_image_file_name).save
      page_image = cover_page.page_images.find_or_initialize_by_image_type('cover')
      page_image.image = image
    end
  end
end

担心的是您的代码运行 *before_validation* 并在此阶段保存任何内容是错误的方式。图书尚未保存,但您已保存其内容...

你必须重写你的回调。让它变得聪明。

于 2012-12-29T02:56:50.950 回答