Reputation: 63
I'm trying to create a simple rails app where user can send me a SMS via Twilio. A user just needs to fill in the form on the home page with his name, email, some text and submit it. I need to create a function that would grab those 3 pieces of information from params, create a text message and send it to my phone number, but I have no idea how to do that.
Those are the form and routes that I tried to create for this:
View: app/views/home/index.html.erb
<div>
<%= form_for @phone, url: 'home/send_text' do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :email %>
<%= f.text_field :email %>
<%= f.label :message %>
<%= f.text_field :message %>
<%= f.submit 'Submit', class: "btn btn-primary" %>
<% end %>
</div>
Routes:
Rails.application.routes.draw do
root 'home#index'
post 'home/send_text'
end
Upvotes: 1
Views: 504
Reputation: 2074
Just follow the below steps :-
Step 1: Create and Configure Twilio Account
Step 2: To integrate Twilio on Rails you have to add twilio-ruby gem to your Gemfile.
gem ‘twilio-ruby’
Step 3: After bundle install you have to use below code
config/initializers/twilio.rb
require 'rubygems'
require 'twilio-ruby'
module TwilioSms
def self.send_text(phone, content)
# phone :- phone number to which you want to send sms
# content :- Message text which you want to send
twilio_sid = "*****" # paste twilio sid
twilio_token = "*****" # paste twilio token
twilio_phone_number = "+1******" # paste twilio number
begin
@twilio_client = Twilio::REST::Client.new twilio_sid, twilio_token
@twilio_client.api.account.messages.create(
:from => twilio_phone_number,
:to => phone,
:body=> content
)
rescue Twilio::REST::TwilioError => e
return e.message
end
return "send"
end
end
Step 4: call this method from where you want to call either controller or model.
TwilioSms.send_text("+91*******", "Hello")
that's it... :)
Upvotes: 2