Class: ActiveRecord::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/active_record_inherit_assoc.rb

Class Method Summary collapse

Class Method Details

.inherits_from(parent_name, options = {}) ⇒ Object

Makes the model inherit the specified attribute from a named association.

parent_name - The Symbol name of the parent association. options - The Hash options to use:

:attr - A Symbol or an Array of Symbol names of the attributes
        that should be inherited from the parent association.

Examples

class Post < ActiveRecord::Base
  belongs_to :category
  inherits_from :category, :attr => :account
end


114
115
116
117
118
119
120
121
122
123
124
# File 'lib/active_record_inherit_assoc.rb', line 114

def self.inherits_from(parent_name, options = {})
  attrs = Array.wrap(options.fetch(:attr))

  before_validation do |model|
    parent = model.send(parent_name)

    attrs.each do |attr|
      model[attr] = parent[attr] if parent.present?
    end
  end
end