Search code examples
ruby-on-railsemailruby-on-rails-4invite

Create many objects from an array of emails in a text area Rails


I am making an app where you can invite participants to a project. I'd like to be able to invite many at once, just like when one types a bunch of email addresses into an email To: field. When Invite form is submitted, then new objects in my :participant table will be created for each corresponding email, with a status_column marked "invited".

I am new and, though I've done an 'update.all' in a form before, I've never 'created' many from one text area.


Solution

  • You could split on every comma and/or every whitespace:

    def create
      params[:project][:participants_addresses] = params[:project][:participants_addresses].split(/\s|,/) if params[:project].try(:[], :participants_addresses).present?
    
      # from now params[:project][:participants_addresses] is an array of Strings
      # you can loop on each email address and create Participant records in the DB,
      # having the status as "invited"
    end