Im creating an api to create a new userS(plural) from an array of emails.
We are assuming that there are no validations other than user requires an email. So all i need is an email to create a user.
Reason i'm doing this is because i'm creating an API.
How do i create users from an array of emails?
Here is the array. I actually have real emails but for this example i will make them up.
# => [
# [0] "email1@example.com.au",
# [1] "email2@example.com.au",
# [2] "email3@example.com",
# [3] "email4@example.com.au",
# [4] "email5@example.com.au"
# ]
To create a user it's just the typical way
User.new(email: 123@example.com)
Thanks in advance for any help.
To save records based on your array, you will want to store that array in a variable (remember that in Ruby, everything is an object). Let's say you have:
emails = ["email1@example.com.au",
"email2@example.com.au",
"email3@example.com",
"email4@example.com.au",
"email5@example.com.au"]
From there you can write a loop that iterates over your lovely array and creates a User for each array item you declared:
emails.each do |e|
User.create(email: e)
end
User. new will not save the records, so please use User. create .
If you just want to save records basing on the emails list(which is an array basing on your description), you just need to do everything like @l0010o0001l said(I love this nickname! :) ). But in my opinion, you could do something more if this api will be provided to others.
The first thing is that you should format the email address with all words in lower-case before you save them. This may do great help whenever save new records or maintain old records. Just like:
emails.each do |email|
User.create(email: email.downcase)
end
Then you need to present result to the one who calls the api. just like: if all the email list was created successfully you can respond with the records amount created successfully. And if some records can not be created(format error, record has existed .etc) you should respond with the error info (you may need to use user.errors.full_messages
to get error messages).
The way to do this is somethign like
user_emails.each do |user_email|
User.create(email: user_emails )
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.