Search code examples
ruby-on-railsruby-on-rails-3inheritanceactiverecordmodels

newbie: how to pass User to Asset model for custom method?


Trying to use current_user.id (devise) inside my asset model, only current_user.id isn't available. How do I make current_user.id available in my Asset model? ( passing user to asset model somehow?)

  after_save :set_photo

  def set_photo
    user = User.find_by_id(1)
    # user = User.find_by_id(current_user.id)  <-- should be this
    user.has_photo = true
    user.save
  end

Solution

  • You cannot use current_user in a callback chain within your model scope. This is because current_user is a property of the request-response cycle. Also, having to use current_user in your model almost certainly means your database design is inadequate or wrong.

    For e.g. in your case, why are you trying to update an attribute of a User when Asset is updated? That is a certain code smell unless they are related.

    A couple of things you can try:

    1. Correct the DB design problem - Define an association between Asset and User. You can then do @asset.user = current_user (or something to this effect) in your controllers.
    2. Ugly, brute force method: Do not depend on callbacks and explicitly call your method in your controllers.