Search code examples
ruby-on-railsrubyruby-on-rails-4seedingrolify

undefined method error on seeding array


I'm implementing a gem called Rolify. I've successfully created a controller and model method to assign a moderator role to users. However, I'm having trouble seeding and testing. For testing I have posted a seperate question.

The idea for seeding is to first create the role in the Role table. Then to take 30 random organizations and for each organization 2 random users, and assign these 2 users a moderator role for that organization. At the end of my seeds file I added:

moderator = Role.create!(:moderator => "moderator") 

organizations = Organization.take(30)
organizations.each do |org|
  2.times do |n|
    user = User.where(usertype: 1).take(1)
    user.add_role :moderator, org
  end
end

The error I get on seeding of creation of the role in the Role table:

ActiveRecord::UnknownAttributeError: unknown attribute 'moderator' for Role.

The error I get on seeding of the second part:

NoMethodError: undefined method 'add_role' for #<Array:0x0000000581f268>

Add_role is a method from rolify and is also used in my controller methods, where it does work.

Any idea what could be causing this seeding problem?


Solution

  • Make sure you have moderator as one of the columns in your db's roles table.

    For second error, line:

    user = User.where(usertype: 1).take(1)
    

    is creating an array object of user(s), not the user. Try changing it to:

    user = User.where(usertype: 1).first