Reputation: 1005
I'm building a test app and came across a problem with Faker gem:
I've created Use model with Devise and used Rolify gem to create roles and then later on will use CanCan to limit user's usage permissions.
So, with Faker I've created a file for my rake task:
namespace :db do
desc "Fill dummy DB"
task :populate => :environment do
require "populator"
require "faker"
password = "password"
User.populate 198 do |user|
user.firstname = Faker::Name.first_name
user.lastname = Faker::Name.last_name
user.email = Faker::Internet.email
user.encrypted_password = User.new(:password => password).encrypted_password
user.phone = Faker::PhoneNumber.phone_number
user.address1 = Faker::Address.street_address
user.city = Faker::Address.city
user.state = Faker::Address.state_abbr
user.zip = Faker::Address.zip_code
user.latitude = Faker::Address.latitude
user.longitude = Faker::Address.longitude
end
end
end
This code works and it creates 198 dummy users...but when I looked into my users_roles table - nothing's there, users don't have roles assigned to them. I've been trying to figure out how to assign a role to user through Faker, but no luck.
I've tried adding user.role_id = User.add_role :user
, but no luck.
Thank you in advance.
Upvotes: 1
Views: 1038
Reputation: 971
I discourage you from using populator gem. There are three reasons to that:
You can construct your database populator with user role adding with code below:
namespace :db do
desc "Fill dummy DB"
task :populate => :environment do
198.times do |n|
user = User.new(
firstname: Faker::Name.first_name,
lastname: Faker::Name.last_name,
email: Faker::Internet.email,
password: "password",
phone: Faker::PhoneNumber.phone_number,
address1: Faker::Address.street_address,
city: Faker::Address.city,
state: Faker::Address.state_abbr,
zip: Faker::Address.zip_code,
latitude: Faker::Address.latitude,
longitude: Faker::Address.longitude )
user.add_role :user
user.save
end
end
end
Please note as I:
Using this construct, you can make more handy things with the User instance, ex. prevent sending a confirmation email when using Devise's :confirmable by invoking user.skip_confirmation!
before saving - what you might find useful.
Consider as well generating emails basing on first_name and last_name already generated by Faker before to have user's name and email inline. To achieve that you may replace
Faker::Internet.email
by
"#{user.first_name}.#{user.last_name}#{n+1}@example.com"
taking advantage of block numerator and therefore creating an unique email.
Upvotes: 1