user938363
user938363

Reputation: 10358

Rails 4 - whitelisted nested attributes nil in create

admin_params is a hash for permitted attributes in Rails 4.2 (see below):

enter image description here

Here is the controller action create:

def create
      @user = User.new(admin_params)
      @user.last_updated_by_id = session[:user_id]
      if @user.save
        redirect_to URI.escape(SUBURI + "/view_handler?index=0&msg=Successfully Saved!")
      else
        flash.now[:error] = t('Data Error. Not Saved!')
        render 'new'
      end
    end

Both nested attributes sys_user_group_id and role_definition_id are expected to be equal to 1 in @user. However both of them become nil after @user = User.new(admin_params). Somehow admin_params did not pass the value of role_definition_id and sys_user_group_id to @user (other non-nested values passes in to @user successfully except 2 nested).

The admin_params is defined as:

def admin_params
      params.require(:user).permit(:name, :login, :email, :update_password_checkbox, :password_confirmation,
                                   :password_new,  :status, :user_type_id, :cell, :allow_text_msg,
                                    :allow_email, :password, :customer_id, :customer_name, :local, user_roles_attributes: [:id, :role_definition_id, :_destroy],
                                    user_levels_attributes: [:id, :sys_user_group_id, :_destroy])                              
    end

Here is rails document we are following about strong parameters of nested attributes. What could cause @user not being assigned for 2 nested attributes? Could be the data structure of admin_params?

Upvotes: 0

Views: 222

Answers (1)

rainbowsorbet
rainbowsorbet

Reputation: 563

Your naming of these attributes may be inconsistent, which would cause the behavior you're observing.

user_role_id does not appear in your list of arguments to #permit. Perhaps that's due to some rails syntactic sugar I don't yet know, given that :id is a value in the user_roles_attributes array. But in that case, I would expect sys_user_group_id (which does an argument to #permit) to be user_levels_sys_user_group_id, because :sys_user_group_id appears in the user_levels_attributes array.

Upvotes: 1

Related Questions