user3100151 user3100151 - 5 months ago 9
Ruby Question

Select body + media_url on each iteration Rails

I am building a functionality to send three MMS (via Twilio) to the phone number entered by the user in a form.

I followed this tutorial from Twilio: https://www.twilio.com/docs/quickstart/ruby/sms/sending-via-rest

The

:from
and
:to
are working no problem and I am able to send the MMS without any problems when the
:body
and
:media_url
are hardcoded like in the example.

I have all my pictures and corresponding texts into a table named Messages and I am able to randomly select two of them by using
Message.order("RANDOM()").limit(2)
, which gives me an array similar to this:

{
:id => 24,
:body => "BODY #1",
:media_url => "MEDIA_URL #1",
:created_at => Fri, 24 Jun 2016 15:21:39 UTC +00:00,
:updated_at => Fri, 24 Jun 2016 15:21:39 UTC +00:00
},
{
:id => 21,
:body => "BODY #2",
:media_url => "MEDIA_URL #2",
:created_at => Fri, 24 Jun 2016 15:21:39 UTC +00:00,
:updated_at => Fri, 24 Jun 2016 15:21:39 UTC +00:00
}
{
:id => 25,
:body => "BODY #3",
:media_url => "MEDIA_URL #3",
:created_at => Fri, 24 Jun 2016 15:41:39 UTC +00:00,
:updated_at => Fri, 24 Jun 2016 15:41:39 UTC +00:00
}


Here's my method to send MMS:

def send_text_message
twilio_sid = ENV["TWILIO_ACCOUNT_SID"]
twilio_token = ENV["TWILIO_AUTH_TOKEN"]
twilio_phone_number = ENV["TWILIO_PHONE_NUMBER"]
sender_number = twilio_phone_number.sample

@twilio_client = Twilio::REST::Client.new(twilio_sid, twilio_token)

3.times {
@twilio_client.account.messages.create(
:from => sender_number,
:to => self.phone,
:body => "I want the corresponding body here",
:media_url => "I want the corresponding media_url here"
)
}


As I said, I have my array of three randomly selected messages from the table and now I need to iterate over this array in order to include them one by one, without creating duplicate as well.

How can I achieve this?

Thank you!

Controller:

def create
@home = Home.new(home_params)

respond_to do |format|
if @home.save
@home.send_text_message
format.html { redirect_to @home, notice: 'MMS Sent' }
format.json { render :show, status: :created, location: @home }
else
format.html { render :new }
format.json { render json: @home.errors, status: :unprocessable_entity }
end
end
end

Answer

I think you can do like this, can't you?

random_messages.each do |message|
  @twilio_client.account.messages.create(
    from:      sender_number,
    to:        self.phone,
    body:      message[:body],
    media_url: message[:media_url]
  ) 
end

Here I suggest that random_messages is the method that returns your random messages array.