Method: Conjoin::ActiveRecord::Form#add_creator_and_updater_for

Defined in:
lib/conjoin/active_record.rb

#add_creator_and_updater_for(model, current_user = nil, current_params) ⇒ Object



115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/conjoin/active_record.rb', line 115

def add_creator_and_updater_for(model, current_user = nil, current_params)
  # set the creator and updater
  id = current_user.try(:id) || ENV["SYSTEM_USER_ID"]

  # Save creator
  if model.respond_to? :creator_id and model.new_record?
    model.set_unrestricted_attribute 'creator_id', id
  end

  # Save updater
  if model.respond_to? :updater_id
    model.set_unrestricted_attribute 'updater_id', id
  end

  return unless current_params
  # loop through associated records
  current_params.each do |name, value|
    name = name.to_s
    if name.end_with?("_attributes")
      associated_name  = name.gsub(/_attributes$/, '')
      associated_model = model.try associated_name

      if associated_model.kind_of? ::ActiveRecord::Base
        new_current_params = (current_params[name.to_sym] || current_params[name])
        if new_current_params.kind_of? Hash
          add_creator_and_updater_for associated_model, current_user, new_current_params
        end
      elsif associated_model.kind_of? ActiveRecord::Associations::CollectionProxy
        new_current_params = (current_params[name.to_sym] || current_params[name])
        associated_model.each_with_index do |current_model, i|
          new_current_params ||= []
          add_creator_and_updater_for current_model, current_user, new_current_params[i]
        end
      end
    end
  end
end