Skip to content

Assign default role to instance after_save (mongoid + rails_admin) #146

@jalberto

Description

@jalberto

I have a devise User model and a Player model, I want to assing a default role to each new created instance of Player for the user that is creating it.

User model is default devise model, Player model is like this:

class Player
  include Mongoid::Document
  include Mongoid::Timestamps
  resourcify

  after_save :assign_role

  field :name,      :type => String
  field :alias,     :type => String
  field :number,    :type => Integer, :default => 0
  field :position,  :type => Integer, :default => 0
  field :age,       :type => String,  :default => 20

  embeds_many :images, as: :imageable, cascade_callbacks: true
  accepts_nested_attributes_for :images # rails_admin need it

  # We store current_user here to assing role
  attr_accessor :r_user_id

  rails_admin do
    list do
      exclude_fields :_id, :created_at, :updated_at, :roles
    end
    create do
      exclude_fields :roles
      field :r_user_id, :hidden do
        visible true
        default_value do
          bindings[:view]._current_user.id
        end
      end
    end
    edit do
      exclude_fields :roles
    end
  end

  private

  # FIXME: THIS DOESN'WORKS only works on 1st item of collection
  def assign_role
    item = self
    return false if item.r_user_id.nil?
    user = User.find(item.r_user_id)
    logger "* False *" unless user.add_role :editor, item
  end
end

The assign_role callback works correctly, it runs every line, even the add_role line. But the role is only saved when the Player colleciton is empty and I'm creating the first item, after the 1st item, callback run without errors, but roles are not saved.

TIA

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions