Sha256: ce8ecb6f9ef05c4c1462972252cb3bb29f64da666e023f03e022f2b7ee344616

Contents?: true

Size: 1.59 KB

Versions: 4

Compression:

Stored size: 1.59 KB

Contents

require 'rails_admin/adapters/active_record/abstract_object'
module RailsAdmin
  module Adapters
    module Mongoid
      class AbstractObject < RailsAdmin::Adapters::ActiveRecord::AbstractObject
        def initialize(object)
          super
          object.associations.each do |name, association|
            if [:has_many, :references_many].include? association.macro
              instance_eval <<-RUBY, __FILE__, __LINE__ + 1
                def #{name.to_s.singularize}_ids
                  #{name}.map{|item| item.id }
                end

                def #{name.to_s.singularize}_ids=(item_ids)
                  items = Array.wrap(item_ids).map{|item_id| #{name}.klass.find(item_id) rescue nil }.compact
                  if persisted?
                    #{name}.substitute items
                  else
                    items.each do |item|
                      item.update_attribute('#{association.foreign_key}', id)
                    end
                  end
                end
RUBY
            elsif [:has_one, :references_one].include? association.macro
              instance_eval <<-RUBY, __FILE__, __LINE__ + 1
                def #{name.to_s}_id=(item_id)
                  item = (#{association.klass}.find(item_id) rescue nil)
                  if persisted?
                    self.#{name} = item
                  else
                    item.update_attribute('#{association.foreign_key}', id) if item
                  end
                end
RUBY
            end
          end
        end

        def destroy
          object.destroy
          object
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 2 rubygems

Version Path
rails_admin-0.0.3 lib/rails_admin/adapters/mongoid/abstract_object.rb
rails_admin-0.0.2 lib/rails_admin/adapters/mongoid/abstract_object.rb
upstream-rails_admin-1.0.2 lib/rails_admin/adapters/mongoid/abstract_object.rb
rails_admin-0.0.1 lib/rails_admin/adapters/mongoid/abstract_object.rb