user3021270
user3021270

Reputation: 78

ActiveAdmin does not save attributes not coming from params

While creating an active admin record, am trying to save an attribute (role_type) which does not come from params.

However, the attribute does not get saved in creation. I have added it to permit_params.

permit_params :email, :password, :password_confirmation, :phone_no, :name, :role_type, role_ids: []

controller do

    def create
      user = User.create(name: params[:user][:name], email: params[:user][:email], password: SecureRandom.hex, role_type: "employee")

      flash[:notice] = "User Created"
      redirect_to admin_user_path(user)
    end
 end

Upvotes: 1

Views: 393

Answers (1)

max
max

Reputation: 102001

If you want to combine a params hash with some attributes that you assign manually the cleanest way is by using a block

permit_params :email, :password, :password_confirmation, :phone_no, :name, :role_type, role_ids: []

controller do

    def create
      user = User.create(permitted_params[:user]) do |u|
        u.password = SecureRandom.hex
      end

      flash[:notice] = "User Created"
      redirect_to admin_user_path(user)
    end
 end

However your password encryption scheme is very naive - I would recommend you use ActiveModel::SecurePassword instead of trying to reinvent the password encryption wheel and creating a insecure authentication system.

Another major issue is that you are not actually checking if the user is created!

permit_params :email, :password, :password_confirmation, :phone_no, :name, :role_type, role_ids: []

controller do

    def create
      user = User.new(permitted_params[:user]) do |u|
        u.password = SecureRandom.hex
      end

      if user.save 
        flash[:notice] = "User Created"
        redirect_to admin_user_path(user)
      else
        render :new
      end
    end
 end

Upvotes: 1

Related Questions