Module: Refinery::PageImages::Extension

Defined in:
lib/refinery/page_images/extension.rb

Defined Under Namespace

Modules: InstanceMethods

Instance Method Summary collapse

Instance Method Details

#has_many_page_imagesObject



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/refinery/page_images/extension.rb', line 4

def has_many_page_images
  has_many :image_pages, :as => :page, :order => 'position ASC'
  has_many :images, :through => :image_pages, :order => 'position ASC'
  # accepts_nested_attributes_for MUST come before def images_attributes=
  # this is because images_attributes= overrides accepts_nested_attributes_for.

  accepts_nested_attributes_for :images, :allow_destroy => false

  # need to do it this way because of the way accepts_nested_attributes_for
  # deletes an already defined images_attributes
  module_eval do
    def images_attributes=(data)
      ids_to_keep = data.map{|i, d| d['image_page_id']}.compact

      image_pages_to_delete = if ids_to_keep.empty?
        self.image_pages
      else
        self.image_pages.where(
          Refinery::ImagePage.arel_table[:id].not_in(ids_to_keep)
        )
      end

      image_pages_to_delete.destroy_all

      data.each do |i, image_data|
        image_page_id, image_id, caption =
          image_data.values_at('image_page_id', 'id', 'caption')

        next if image_id.blank?

        image_page = if image_page_id.present?
          self.image_pages.find(image_page_id)
        else
          self.image_pages.build(:image_id => image_id)
        end

        image_page.position = i
        image_page.caption = caption if Refinery::PageImages.captions
        image_page.save
      end
    end
  end

  include Refinery::PageImages::Extension::InstanceMethods

  attr_accessible :images_attributes
end