To remove the empty string from the array, use #reject
.
params["lalaemail"]["to"].reject(&:blank?)
But let's address your second question before we clean that up:
First ensure that your Email
table has to
column with array
set to true
—if it doesn't, create a migration for it (and maybe give it a better name, like recipients
):
class AddRecipientsColumnToEmail < ActiveRecord::Migration[5.1]
def change
add_column :emails, :recipients, :text, array: true, default: []
end
end
After you run that migration, each instance of an email will have the ability to save as many recipients
as you want.
Now, let's circle back to using #reject
.
Instead of manipulating the dirty recipients
array you get back from the view in your controller, let's offload removing the empty strings to the Email
model:
Email.rb
class Email < ApplicationRecord
# Your associations
# Your validations
# Define a before_validation hook that will sanitize your input
# Example:
before_validation :sanitize_recipients
# More public model methods you may have
private
# Define your sanitation method; consider if there's anything else
# you'd want to do to clean the data--perhaps remove duplicates?
#
# Returns an Array.
def sanitize_recipients
self.recipients = recipients.reject(&:blank?)&.uniq
end
end
If you're unfamiliar with before_validation
--it's built-in to Rails and basically tells your model: "Hey wait, before you check this data, let me do this first.", where "this" can be any method you define. In this case, we defined a method to sanitize the recipients
Array of any duplicate or blank values.
And voila, the empty string you get back is no longer an issue, and you have the ability to save all of an email's recipients.