Daniel May
Daniel May

Reputation: 2262

passing current_user to model via callback

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?

Upvotes: 2

Views: 1274

Answers (1)

santuxus
santuxus

Reputation: 3702

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

Upvotes: 1

Related Questions