In my rails application I am having users module which is dependent on roles model.Both are integrated via user_role_assignment model.i.e An user has many roles associated via the user roles assignment.
I am in need to generate a migration to create some default users.
The problem I a facing is if I try to create a user via console,I get an error saying “roles can’t be blank.
u=User.create(:name => "ramyameena", :email => "ramyameena@sandvine.com",:password=>"sandvine",:roles=>{:id=>2,:name=>"Tester"})
=> #<**User id: nil**, name: "ramyameena", created_at: nil, updated_at: nil, email: "ramyameena@sandvine.com", encrypted_password: "$2a$10$qIfRLKZlxviag9E0Gzvp8e3VKkOCaXraP7PnJC6vGMN....", reset_password_token: nil, remember_token: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil>
irb(main):012:0> u.errors.inspect
=> "#<OrderedHash **{:roles=>[\"can't be blank\"]**}>"
My users model:
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
validates :name, :presence => true, :uniqueness => true
validates :roles, :presence => true
has_many :user_role_assignments
has_many :roles, :through => :user_role_assignments
has_many :tester_release_assignments
has_many :releases, :through => :tester_release_assignments
has_many :releases
has_many :ic_runs
accepts_nested_attributes_for :user_role_assignments
attr_accessible :email, :name, :password, :password_confirmation, :role_ids
You have
accepts_nested_attributes_for :user_roles_assignmentsbut on create you’re passing in roles, not user_roles_assignments. I’d check that you aren’t missingaccepts_nested_attributes_for :rolesor a helper method of some sort…Alternatively, you’ll need to do the roles separately. eg