Umer Hassam
Umer Hassam

Reputation: 1330

Rails Trying to access parameters in Model

I've created a User model through Devise gem

My relationships are setup as:

Now everytime a User is created I am calling the method cup that creates a UserProfile as well. The problem is that I can't access anything other than devise's own parameters in the Model.

For example I have a drop down to select for Role but i cant access its selected value

My aim is to do something like:

  def cup
    if role.title == 'this'
      create_user_profile(:username => 'username01')
    else
      create_user_profile(:username => 'username02')
    end
  end

This is what the model looks like:

class User < ActiveRecord::Base

  has_and_belongs_to_many :roles
  belongs_to :batch
  has_one :user_profile

  after_create :cup

  def cup
    create_user_profile(:username => 'username')

  end

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
end

My parameters look like this:

{"utf8"=>"✓", "authenticity_token"=>"TbsLJxZB2aeDgj8RitTRKURCc3KODCKpv/xphwhAaIw=", "users"=>{"username"=>"rfdsfew", "role_id"=>"1", "batch_id"=>"1"}, "user"=>{"email"=>"[email protected]", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign up"}

I can access the params in user hash but not in users hash

My guess is that, this is because the users hash is not allowed in devise controller, since I can't access devise's controller I have no idea how to permit the users hash.

And I found this on the internet but it didn't work:

before_filter :configure_permitted_parameters, if: :devise_controller?

protected

def configure_permitted_parameters
  devise_parameter_sanitizer.for(:sign_up) << :username
end

Upvotes: 2

Views: 1528

Answers (1)

Frederick Cheung
Frederick Cheung

Reputation: 84114

The main thing is that the extra parameters should be part of params[:user], so change your calls to collection_select.

Next you need to make sure that devise allows those extra parameters - that's the purpose of

 devise_parameter_sanitizer.for(:sign_up) << :username

which you would need to do for each extra parameter. But for array parameters you need to use the longer form:

devise_parameter_sanitizer.for(:sign_up) {|u| u.permit(:email, :password, :username, :batch_id, :role_ids => [])}

Which brings me to the last change you need: your association with roles is has_and_belongs_to_many: you cannot assign role_id, you must assign role_ids, which must be an array.

You need to change the name used by the form element to role_ids and for rails to parse it as an array you need to add [] to the end of it. If you pass :multiple => true to the select helpers they should do this for you.

Upvotes: 0

Related Questions