Project

General

Profile

import users and push them to a defout project and give them roles ,thanks

Added by yz li almost 6 years ago

I want import numerous user from CSV file,like this:

login password lastname firstname mail admin project role
NO.31 111 john doe 0 default manager

and I have find a plugin :User CSV Import Plugin [[http://www.redmine.org/plugins/user_import_plugin]]
but it can just ipmort usrs cannot push them to my default project and set role.

is there other plugin have the function I need ?or How can I amend this plugin ?
Somebody help!Thank you very much!


Replies (1)

RE: import users and push them to a defout project and give them roles ,thanks - Added by Martin Denizet (redmine.org team member) almost 6 years ago

Hello,
Code bellow is untested, use at your own risks, make sure to backup before doing anything else
I'd probably be tempted to run something like that in the Rails console or in a Rake task:

require 'csv'
source = CSV.read('newusers.csv')

source.each_with_index do |line, i|
  p "Source line #{i}" 
  # Some vars for better readability
  project_id = line[6]
  role_id = line[7]
  login = line[0]

  u = User.new(login: login, admin: line[5], 
    mail: line[4], 
    firstname:line[2] , lastname:line[3])

  #password cannot be mass assigned so it needs to be specified separately
  u.password=line[1]

  if u.save
    p "Saved #{login}" 
    # Add role to project
    m = Member.new(:project => Project.find(project_id), :user_id => u.id)
    m.role_ids=[role_id]
    # Handling save errors here would be nice
    m.save
  else
    p u.errors.messages.inspect #Displays saving errors
  end

end

Note that here I assume that the role id is given and not the label.
Hope it helps,

Cheers,

    (1-1/1)