2

I have a couple of callbacks that log activity on create/update:

class Projelement
  ..
  after_create   { |p| p.log_projelement_activity "created" }
  after_update   { |p| p.log_projelement_activity "edited"  }

I need to augment the design to pass the current_user (Devise) to log_projelement_activity to record the user at the time of create/update.

I'm trying to pass the current_user from the controller to the model and the callbacks via a virtual attribute. But this isn't working.

The code:

class Projelement
  attr_accessor :modifying_user

  after_create   { |p| p.log_projelement_activity "created", modifying_user }
  after_update   { |p| p.log_projelement_activity "edited",  modifying_user }

  def log_projelement_activity(op_type, user)
    @a = Activity.new
    @a.user = user
  end
end


class MilestoneController
  ..
  def create
    @milestone = Milestone.new(params[:milestone])
    @milestone.modifying_user = current_user
  end
end

Each create/update Activity has expected values, except that the user field is nil.

What am I missing?

Daniel May
  • 2,192
  • 5
  • 25
  • 43
  • 1
    You mean `Projelement.new`, right? Try adding user to `params`, `@milestone = Projelement.new(params[:milestone].merge(:modifying_user => current_user))`. – shime Apr 02 '12 at 14:20
  • Thanks. I'm instantiating a ``Milestone`` which is a type of ``Projelement``. This has a few extra attributes and all other attributes are being set properly except for ``modifying_user``. Unfortunately your suggestion didn't work: how is it different to what I am doing before? – Daniel May Apr 02 '12 at 19:20

1 Answers1

1

You could use userstamp. I think that this gem does exactly what you need ;) I used it with devise and it... just works perfectly!

santuxus
  • 3,662
  • 1
  • 29
  • 35
  • Thanks @santuxus. Have been looking through it: finding it a bit hard understanding the usage as it's written a bit abstractly. Am also using ``Mongoid``. It does seem to be used by a lot of people. – Daniel May Apr 02 '12 at 19:23
  • https://github.com/msaffitz/userstamp-mongoid should be for you. I haven't used it and the main repo is 2-years-old, but I suppose one of the forks should be ok and up to date. – santuxus Apr 03 '12 at 08:02
  • Thanks, yeah I was googling around and found it too – Daniel May Apr 03 '12 at 12:07