ruby,forms,ruby-on-rails-4,controller,twilio , Rails 4: Group Text Message Strategy - Passing Multiple Records to a Controller

Rails 4: Group Text Message Strategy - Passing Multiple Records to a Controller


Tag: ruby,forms,ruby-on-rails-4,controller,twilio

My Rails app works by letting Users create Clients and then send or schedule text_messages using Twilio. Creating one Client and then generating one text_message record works great. The User owns Clients which owns Text_Message.

My next feature to tackle is to allow a User to choose which Clients they want to send a group text message too. I want to generate a text_message record for each Client (with the same content and scheduled_date). Saved text_messages are getting added to a Sidekiq queue.

I need some help (please) on the strategy on this. How do I implement Group_Text while keeping the code dry and continuing to generate records for the text_message table? How do I pass multiple selected clients from a form/view to a controller to create the records while using the logic from the Text_Message model? Thanks for the pointers!

Relevant code


    ActiveRecord::Schema.define(version: 20141207214913) do

      # These are extensions that must be enabled in order to support this database
      enable_extension "plpgsql"

      create_table "action_plans", force: true do |t|
        t.integer  "client_id"
        t.text     "description"
        t.datetime "created_at"
        t.datetime "updated_at"

      add_index "action_plans", ["client_id"], name: "index_action_plans_on_client_id", using: :btree

      create_table "clients", force: true do |t|
        t.integer  "user_id"
        t.string   "first_name",    null: false
        t.string   "last_name",     null: false
        t.string   "phone",         null: false
        t.string   "salesforce_id", null: false
        t.string   "email"
        t.datetime "created_at"
        t.datetime "updated_at"
        t.text     "contact_id"

      add_index "clients", ["user_id"], name: "index_clients_on_user_id", using: :btree

      create_table "coach_emails", force: true do |t|
        t.integer  "user_id"
        t.string   "email",            null: false
        t.string   "coach_firstname"
        t.string   "client_lastname"
        t.string   "client_firstname"
        t.text     "content",          null: false
        t.boolean  "sentstatus"
        t.datetime "created_at"
        t.datetime "updated_at"

      add_index "coach_emails", ["user_id"], name: "index_coach_emails_on_user_id", using: :btree

      create_table "goals", force: true do |t|
        t.integer  "action_plan_id"
        t.text     "description"
        t.datetime "created_at"
        t.datetime "updated_at"

      add_index "goals", ["action_plan_id"], name: "index_goals_on_action_plan_id", using: :btree

      create_table "steps", force: true do |t|
        t.integer  "goal_id"
        t.text     "description"     "due_by"
        t.boolean  "complete",    default: false
        t.datetime "created_at"
        t.datetime "updated_at"

      add_index "steps", ["goal_id"], name: "index_steps_on_goal_id", using: :btree

      create_table "text_messages", force: true do |t|
        t.integer  "client_id"
        t.text     "content"
        t.boolean  "incoming_message"
        t.datetime "created_at"
        t.datetime "updated_at"     "scheduled_date"
        t.boolean  "sentstatus"
        t.integer  "step_id"
        t.string   "phone"

      add_index "text_messages", ["client_id"], name: "index_text_messages_on_client_id", using: :btree

      create_table "users", force: true do |t|
        t.string   "email",                  default: "", null: false
        t.string   "encrypted_password",     default: "", null: false
        t.string   "reset_password_token"
        t.datetime "reset_password_sent_at"
        t.datetime "remember_created_at"
        t.integer  "sign_in_count",          default: 0,  null: false
        t.datetime "current_sign_in_at"
        t.datetime "last_sign_in_at"
        t.inet     "current_sign_in_ip"
        t.inet     "last_sign_in_ip"
        t.string   "first_name"
        t.string   "last_name"
        t.datetime "created_at"
        t.datetime "updated_at"
        t.string   "role"
        t.string   "title"
        t.string   "confirmation_token"
        t.datetime "confirmed_at"
        t.datetime "confirmation_sent_at"
        t.string   "unconfirmed_email"

      add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree
      add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree



    require 'twilio-ruby'
    require 'date'

    class TextMessage < ActiveRecord::Base

      belongs_to :client, dependent: :destroy
      belongs_to :step, dependent: :destroy
      has_many :coach_emails

    before_save :grab_phone

      def grab_phone = phone

      def send_text_message(message, phone)

        twilio_sid = ENV["TWILIO_ACCT_SID"]
        twilio_token = ENV["TWILIO_AUTH_TOKEN"]
        twilio_phone_number = ENV["TWILIO_PHONE_NUMBER"]

          @twilio_client =, twilio_token)

            :from => "+1#{twilio_phone_number}",
            :to => phone,
            :body => message)

          rescue Twilio::REST::RequestError => e
            puts e.message

        if e != "400" || e != "500"
          self.sentstatus = true


    Rails.application.routes.draw do

    require 'sidekiq/web'

      devise_for :users, :path => '',
        :path_names => {:sign_in => 'login', :sign_out => 'logout'}, 
        :controllers => { registrations: 'registrations' }

      authenticate :user do
        mount Sidekiq::Web => '/sidekiq'

      resources :clients do
        resources :action_plans, shallow: true, except: [:index] 

      resources :action_plans, shallow: true, only: [] do
        resources :goals, shallow: true, except: [:index]

      resources :goals, shallow: true, only: [] do
        resources :steps, shallow: true, except: [:index, :destroy]

      resources :steps, shallow: true, only: [] do
        resources :text_messages, shallow: true, except: [:index, :destroy]

      get "text_messages/receive"
      match '/receivetext' => 'text_messages#receive', :via => :post

      resources :clients do
        collection do
          post :welcome

      get 'about' => 'welcome#about'

      root to: 'welcome#index'



I figured out that I need to add to the TextMessage controller (#groupnew and #groupcreate).

New Routes

get 'group_new' => 'text_messages#group_new' 
post 'group_create' => 'text_messages#group_create'

Updated TextMessage Controller

def group_new
  @clients = current_user.clients.order(:last_name)
  @text_message = 

def group_create
  client_hash = params[:client_id]

  client_hash.each do |client|
    @client = Client.find(client)
    content = params[:text_message][:content]

    @text_message =
    @text_message.incoming_message = false
    @text_message.sentstatus = false =

    if @text_message.scheduled_date == nil 
      @text_message.scheduled_date =
      # print time in Pacific time
      @text_message.scheduled_time ="Pacific Time (US & Canada)")
  redirect_to clients_path

Group text now works :)


For loop with flexible stop variable

I need to write a loop for x in (1..y) where the y variable can be changed somehow. How can I do that? For example: for x in (1..y/x) But it does not work. ...

Ruby- get a xml node value

can someone help me in extracting the node value for the element "Name". Type 1: I am able to extract the "name" value for the below xml by using the below code <Element> <Details> <ID>20367</ID> <Name>Ram</Name> <Name>Sam</Name> </Details> </Element> doc = Nokogiri::XML(response.body) values = doc.xpath('//Name').map{ |node| node.text}.join ',' puts values...

rails - NameError (undefined local variable or method while using has_many :through

My rails app gives following error: NameError (undefined local variable or method 'fac_allocs' for #): app/models/room.rb:4:in '' app/models/room.rb:1:in '' app/controllers/rooms_controller.rb:3:in 'index' room.rb file class Room < ActiveRecord::Base has_many :bookings has_many :fac_allocs has_many :facs, :through => fac_allocs end ...

Allowing some enabled and disabled option on collection_select

I am trying to populate a dropdown box on a view that has all the states. This works just fine: <%= f.collection_select :state_id, @states, :id, :name %> Now, I need to make the following: Some states are going to be disabled for choosing, but they still have to appear on...

Stack level too deep because recursion

I have a model named Tweet. The columns of the Tweet model are: -id -content -user_id -picture -group -original_tweet_id Every tweet can have one or multiple retweets. The relation happens with the help of original_tweet_id. All the tweets have original_tweet_id nil , whilst the retweets contain the id of the...

Seeding fails validation for nested tables (validates_presence_of)

An Organization model has a 1:many association with a User model. I have the following validation in my User model file: belongs_to :organization validates_presence_of :organization_id, :unless => 'usertype==1' If usertype is 1, it means the user will have no organization associated to it. For a different usertype the presence of...

How to pivot array into another array in Ruby

I have a multidimensional array like this one : myArray = [["Alaska","Rain","3"],["Alaska","Snow","4"],["Alabama","Snow","2"],["Alabama","Hail","1"]] I would like to end up with CSV output like this. State,Snow,Rain,Hail Alaska,4,3,nil Alabama,2,nil,1 I know that to get this outputted to CSV the way I want it I have to have output array like this: outputArray =[["State","Snow","Rain","Hail"],["Alaska",4,3,nil],["Alabama",2,nil,1]]...

Ruby access words in string

I don't understand the best method to access a certain word by it's number in a string. I tried using [] to access a word but instead it returns letter. puts s # => I went for a walk puts s[3] # => w ...

Heroku RAM not increasing with upgraded dynos

I have a massive function i have been calling manually through the heroku rails console. I have been receiving the error rapid fire in my logs: 2015-06-22T14:56:42.940517+00:00 heroku[run.9877]: Process running mem=575M(112.4%) 2015-06-22T14:56:42.940517+00:00 heroku[run.9877]: Error R14 (Memory quota exceeded) A 1X dyno is suppose to have 512 MB of RAM. I...

Split an array into slices, with groupings

I've got some Ruby code here, that works, but I'm certain I'm not doing it as efficiently as I can. I have an Array of Objects, along this line: [ { name: "foo1", location: "new york" }, { name: "foo2", location: "new york" }, { name: "foo3", location: "new york"...

Rails shared controller actions

I am having trouble building a controller concern. I would like the concern to extend the classes available actions. Given I have the controller 'SamplesController' class SamplesController < ApplicationController include Searchable perform_search_on(Sample, handle: [ClothingType, Company, Collection, Color]) end I include the module 'Searchable' module Searchable extend ActiveSupport::Concern module ClassMethods def...

Javascript into HTML form

Hi I am trying to implement a HTML form. Let's suppose it has 4 fields- Name , Age , City (dropdown- contains A,B,C,D) and Region. I want Region field to appear only when City selected is A or B and disappears if city is changed to C and D. Could...

Loop until i get correct user

I have users stored in Redis and want to be able to call only certain subsets from a set, if i don't get the correct user back i want to put it back in the set and then try again until i get one of the desired users @redis =...

Map with accumulator on an array

I'm looking to create a method for Enumerable that does map and inject at the same time. For example, calling it map_with_accumulator, [1,2,3,4].map_with_accumulator(:+) # => [1, 3, 6, 10] or for strings ['a','b','c','d'].map_with_accumulator {|acc,el| acc + '_' + el} # => ['a','a_b','a_b_c','a_b_c_d'] I fail to get a solution working. I...

Ruby: How to copy the multidimensional array in new array?

seating_arrangement [ [:first, :second, :none], [:first, :none, :second], [:second, :second, :first], ] I need to copy this array into new array. I tried to do it by following code: class Simulator @@current_state def initialize(seating_arrangement) @@current_state = seating_arrangement.dup end But whenever I am making any changes to seating_arrangement current_state changes automatically....

String#scan not capturing all occurences

I'm facing a very strange behaviour with ruby String#scan method return. I have this code below and I can't find out why "scan" doesn't return 2 elements. str = "10011011001" regexp = "0110" p str.scan(/(#{regexp})/) ==> [["0110"]] String "str" clearly contains 2 occurences of pattern "0110". I want to fetch...

Show only the requested forms using JS

As the image below illustrates, I have two forms and two buttons. Currently all the forms are visible. How can I only show the requested form "according to the option they have selected (from the blue buttons on the top)"? So, if the user clicked on the "send an invite"...

Keep leading zeroes when converting string to integer

For no particular reason, I am trying to add a #reverse method to the Integer class: class Integer def reverse self.to_s.reverse.to_i end end puts 1337.reverse # => 7331 puts 1000.reverse # => 1 This works fine except for numbers ending in a 0, as shown when 1000.reverse returns 1 rather...

Get X days out of an Array

I have an array filled with Datetime objects: [Mon, 22 Jun 2015, Tue, 23 Jun 2015, Wed, 24 Jun 2015, Thu, 25 Jun 2015, Fri, 26 Jun 2015, Sat, 27 Jun 2015, Sun, 28 Jun 2015] I know how to select what I want from the array ex:{|x|x.monday? ||...

How to handle backslash “\” escape characters in q string and heredocument

Ruby Newbie here. I do not understand why Ruby looks inside %q and escapes the \. I am using Ruby to generate Latex code. I need to generate \\\hline which is used in Latex for table making. I found \\\hline as input generated \hline even though the string was inside...

Heroku rake db:migrate failing - uninitialized constant

My app is working fine locally and my push to Heroku was successful. But, when I run heroku run rake db:migrate, I get the following error: NameError: uninitialized constant AddWeightToExercises Here is the failed migration: class AddWeightToExercise < ActiveRecord::Migration def change add_column :exercises, :weight, :float end end edit: Thanks for...

How could I padding spaces to a fix length

I need all strings' length with 5 Original [477, 4770,] Expected ["477 ", "4770 "] How could I do it with Ruby ?...

Rails Association Guidance [on hold]

I am new to rails 4. I have gone through lots of tutorials and trying to solve below scenario. But still no success. Can anybody point me in the right direction. How to handle associations for below scenario. Scenario: 1. Patient can have many surgeries. 2. Surgery has two types...

Rails basic auth not working properly

I am building a small API that uses basic authentication. What I have done, is that a user can generate a username and password, that could be used to authenticate to the API. However I have discovered that it is not working 100% as intended. It appears that a request...

Rails: get f.range_field to submit null or nil as default value

In my app, I have a range_field where a user can select 0..100. But if they don't select anything, I want the form to submit "null" or nil as the value rather than a numerical value. Is this possible? If I use the below syntax, then everything works except value...

Symfony 2 unable to pass entity repository to form

I have a form with a drop down and a set of checkboxes, i've used entity form field type to get the values via DB. it works with one of the entity but not with the other. i have this code seperately inside AddBadgesType there is NO AddBadges entity <?php...

is there an equivalent of the ruby any method in javascript?

Is there an equivalent of ruby's any method for arrays but in javascript? I'm looking for something like this: arr = ['foo','bar','fizz', 'buzz'] arr.any? { |w| w.include? 'z' } #=> true I can get a similar effect with javascript's forEach method but it requires iterating through the entire array rather...

Ruby on Rails - Help Adding Badges to Application

I'm creating a rails application that is a backend for a mobile application. The backend is implemented with a RESTful web API. Currently I am trying to add gamification to the platform through the use of badges that can be earned by the user. Right now the badges are tied...

Run AJAX function on form submit button after javascript confirm() cancel

I have a form where and AJAX function runs on form submission to make sure that the data in the form doesn't conflict with data in the database. If a conflict is found, the AJAX function pops up a confirm() box. If the user clicks "OK", the form is submitted....

Entering data into mysql database using php

Customer will complete a form and enter a pathway where they will want the CSV to be exported to. The pathway is entered using the top section of the php (below): <form action="register.php" method="post"> Enter file pathway where CSV will be saved: <input type="text" name="username" required="required"/> <br/> <input type="submit" value="Enter"/>...

edit first line of multiple files in place with a ruby one-liner

I can edit multiple files in place using the -p -i -e command line options: ruby -pi -e 'sub(/a/,"b")' file* How can I edit only the first line of each file? This works for one file only: ruby -pi -e 'sub(/^/,"New line goes at top\n") if $. == 1' file1...

Javascript/jQuery form validation

I got most of this form validation to work properly but the only issue is that when the form detects an error on submit and the user corrects the mistake, the error text won't go away. This can be confusing for the user but I can't seem to figure out...

Ruby gsub group parameters do not work when preceded by escaped slashes

I am trying to perform a trivial substitution, that in any other language I have come across, work as per the documentation. However, my substitution fails for some reason. The documentation examples list: "hello".gsub(/[aeiou]/, '*') #=> "h*ll*" "hello".gsub(/([aeiou])/, '<\1>') #=> "h<e>ll<o>" "hello".gsub(/./) {|s| s.ord.to_s + ' '} #=> "104 101...

Appending an element to a page in VoltRb

I'm trying to append an element to one of my pages in a Volt project, via opal-browser, like so: if RUBY_PLATFORM == 'opal' require 'browser' $document.body << my_dom_element.to_n end # controller code below Unfortunately, I'm getting an error: [Error] TypeError: null is not an object (evaluating 'value.nodeType') (anonymous function) (main.js,...

Rails less url path change

Developing a Rails application with the less-rails gem I found something unusual : // app/assets/common/css/desktop/typo.less @font-face{ font-family:'SomeFont'; src:url("fonts/db92e416-da16-4ae2-a4c9-378dc24b7952.eot?#iefix"); // ... } The requested font is app/assets/common/css/fonts/db92e416-da16-4ae2-a4c9-378dc24b7952.eot This font is compiled with less and the results is : @font-face { font-family: 'SomeFont'; src: url("desktop/fonts/db92e416-da16-4ae2-a4c9-378dc24b7952.eot?#iefix"); //... } Do you know why is...

regex to pull in number with decimal or comma

This is my line of code: col_value = line_item[column].scan(/\d+./).join().to_i When I enter 30,000 into the textfield, col_value is 30. I want it to bring in any number: 30,000 30.5 30.55 30000 Any of these are valid... Is there a problem with the scan and or join which would cause it...

Can't map a range of dates in Ruby/Rails

I'm trying to map a range of dates and pass them to my view as an array, as follows: from, to = Date.parse("2014-01-01"), Date.yesterday date_range = ( @mapped_dates = {|date| date.strftime("%b %e")} I reference them in some JS in my view as follows: dateLabels = <%= raw @mapped_dates.to_json %>;...

Ruby boolean logic: some amount of variables are true

Let say I have 3 variables: a, b, c. How can I check that just zero or one of them is true?...

In Ruby how to put multiple lines in one guard clause?

I have the following line of code : if params[:"available_#{}"] == 'true' @deliverycharge = @product.deliverycharges.create!(districtrate_id: delivery_custom_price(district) end Rubocop highlight it and asks me to use a guard clause for it. How can I do it? EDIT : Rubocop highlighted the first line and gave this message Use a guard...

Angular submit not called when required fields not filled

I'm creating a form in Angular with Ionic. I don't want a red error class to be displayed unless a user has submitted the form. As such, my code looks like this: <form ng-submit="submit()" name="form"> <ion-radio ng-repeat="item in items" ng-model="data.type" name="type" ng-value="item.value" ng-class="{'error' : form.type.$invalid && formSubmitted }" </form> And...

Same enum values for multiple columns

I need to do something like this: class PlanetEdge < ActiveRecord::Base enum :first_planet [ :earth, :mars, :jupiter] enum :second_planet [ :earth, :mars, :jupiter] end Where my table is a table of edges but each vertex is an integer. However, it seems the abvove is not possible in rails. What might...

How to get return value from a forked / spawned process in Ruby?

My simple test program: pid = Process.spawn("sleep 10;date") How can I place the output (eg stdout) of the "date" command in a variable when it is available? I don't want to use a file for the data exchange....

Rails - link_to path based on object's name + refactoring multiple custom actions

I'm looking to simplify the link_to path based on thr object's name and also am looking into refactoring multiple custom actions. I've managed to get this working below. <% ServiceMenu.all.each do |menu| %> <tr class=" <%= cycle('odd', 'even') %>"> <td><%= link_to, ("tech/""#{}") %></td> </tr> <% end %> I feel...

Form not submitted using jquery

I have following form, <form method="post" action="test.php" id="offer1Form"> <input type="hidden" name="c" value="3883316"> <input type="hidden" name="qtyadd" id="qtyadd" value="1"> <input type="hidden" name="buyid" id="buyid" value="multi"> <input type="hidden" name="multi" id="multi" value="11,1;150,1;182,1;27,1; "> <input type="hidden" name="promocode" value="<?php echo $promote_code1?>"> <input type="hidden" name="continue" value="<?php echo "...

On rendering from controller, current_page method does not seem to work

I have a navigation bar included in application.html.erb. Because for some pages, such as the signup page, I need to place additional code inside the navigation bar, I have excluded those pages for showing the navigation bar through application.html.erb and instead included it in their respective view pages. See code...

Using Ruby Pathname to access relative directory

Given I have a relative path pointing to a directory how can I use it with Ruby's Pathname or File library to get the directory itself? p ='dir/') p.dirname => . => false I have tried './dir/', 'dir/', 'dir'. What I want is p.dirname to return 'dir'. I...

Call method to generate arguments in ruby works in 1.8.7 but not 1.9.3

This is something that I had working in ruby 1.8.7, but no longer works in 1.9.3, and I am not sure what changes make this fail. Previously, I had something like this myFunction(submitArgs()) where submitArgs was a helper method that could be called with some options def submitArgs(args={}) #Some logic/manipulations...

Get the actual value of a boolean attribute

I have the span: <span disabled="disabled">Edit Member</span> When I try to get the value of the disabled attribute: page.in_iframe(:id => 'MembersAreaFrame') do |frame| expect(page.span_element(:xpath => "//span[text()='Edit Member']", :frame => frame).attribute('disabled')).to eq("disabled") end I get: expected: "disabled" got: "true" How do I get the value of specified attribute instead of a...

What is Rack::Utils.multipart_part_limit within Rails and what function does it perform?

Rack::Utils.multipart_part_limit is set to 128 by default. What purpose does the value have and what effect does it have within the Rails system?...

Make instance variable accessible through hash in Ruby

In Rails, ActiveRecord objects, attributes are accessible via method as well as through Hash. Example: user = User.first # Assuming User to be inheriting from ActiveRecord::Base # Accessing attribute 'name' via method user[:name] # Attribute 'name' is accessible via hash as well How to make instance variables accessible through...