アプリで結合テーブル レコードを自動保存する方法がわかりません。ユーザーが本を作成できるようにするアプリケーションを構築しています。ページを作成し、画像のギャラリーをアップロードしてから、画像をページに接続します。すべての本には表紙があり、表紙の画像があります。
私の目標は、本の cover_image_file_name を設定し、本の保存時にサブモデルの変更を保存できるようにすることです。(実際に添付された画像を扱わないように、例を絞り込みました - それは問題ではありません)。
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 を使用しています。